Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create meta annotations on field level?

I have this hibernate class with annotations:

@Entity
public class SimponsFamily{

  @Id
  @TableGenerator(name = ENTITY_ID_GENERATOR,
                table = ENTITY_ID_GENERATOR_TABLE,
                pkColumnName = ENTITY_ID_GENERATOR_TABLE_PK_COLUMN_NAME,
                valueColumnName = ENTITY_ID_GENERATOR_TABLE_VALUE_COLUMN_NAME)
  @GeneratedValue(strategy = GenerationType.TABLE, generator = ENTITY_ID_GENERATOR)
  private long id;

  ...
}

Since I don´t won´t to annotate every id field of my classes that way, I tried to create a custom anotation:

@TableGenerator(name = ENTITY_ID_GENERATOR,
            table = ENTITY_ID_GENERATOR_TABLE,
            pkColumnName = ENTITY_ID_GENERATOR_TABLE_PK_COLUMN_NAME,
            valueColumnName = ENTITY_ID_GENERATOR_TABLE_VALUE_COLUMN_NAME)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface EntityId {

    @GeneratedValue(strategy = GenerationType.TABLE, generator = ENTITY_ID_GENERATOR)
    public int generator() default 0;

    @Id
    public long id() default 0;
}

so that I can use this annotation in my class:

 @Entity
 public class SimponsFamily{


 @EntityId
 private long id;

  ...
}

I do have to write the @Id and the @GeneratedValue annotions on field level since they do not support the TYPE RetentionPolicy. This solutions seems to work.

My questions:

  • How are the field level annotations in my custom annotations(and values) transferred to my usage of EntityId annotation?

  • What about the default values which I set in my custom annotation, are they used since I do not specify attributes at the usage?

  • It is a preferred way to use annotations on field level in annotations?

like image 364
thilko Avatar asked May 29 '13 09:05

thilko


1 Answers

I think I can aswer your third question.

One common way to do what you want (avoid duplicating ID mapping) is to create a common superclass that holds the annotated id and version (for optimistic locking) fields, and then have all persistent objects extend this superclass. To ensure the superclass is not considered an Entity on its own, it must be annotated with @MappedSuperclass.

Here is a sample (sorry for typos, I don't have an IDE at hand right now) :

@MappedSuperclass
public class PersistentObject {

    @Id // Put all your ID mapping here
    private Long id;

    @Version
    private Long version;

}

@Entity
public class SimpsonsFamily extends PersistentObject {        
    // Other SimpsonFamily-specific fields here, with their mappings    
}
like image 55
Olivier Croisier Avatar answered Oct 09 '22 12:10

Olivier Croisier