How to create meta annotations on field level?

情到浓时终转凉″ 提交于 2019-12-06 01:47:42

问题


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?


回答1:


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    
}


来源:https://stackoverflow.com/questions/16810269/how-to-create-meta-annotations-on-field-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!