How to create field level meta annotations?

I have this hibernation 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 want to comment out all the id fields of my classes this way, I tried to create a normal annotation:

 @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 need to write @Id and @GeneratedValue at the field level, as they do not support TYPE RetentionPolicy. These solutions seem to work.

My questions:

  • How do field level annotations in my user annotations (and values) get transferred to my use of EntityId annotations?

  • What about the default values ​​that I set in my user annotation, are they used since I don't specify attributes when used?

  • Is this the preferred way to use field level annotations in annotations?

+6
source share
1 answer

I think I can answer the third question.

One common way to do what you need (to avoid duplicate identifier matching) is to create a common superclass that contains id and version annotated fields (for optimistic locking), and then all persistent objects extend that superclass so that the superclass is not considered Entity by itself , it must be annotated with @MappedSuperclass .

Here is an example (sorry for typos, I don't have an IDE 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 } 
+4
source

Source: https://habr.com/ru/post/946069/


All Articles