Annotation Aggregation

I have several classes where I always have the same annotations for the fields that define the primary key of the table, for example:

@Id @Type(type = "uuid-binary") @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2", parameters = { @Parameter( name = "uuid_gen_strategy_class", value = "org.hibernate.id.UUIDGenerationStrategy") }) @Column(name="PROFILE_ID", unique = true) @NotNull(message = "we have one message" , payload =Severity.Info.class) private UUID profileId; 

Now I'm looking for a way to combine all of these annotations into one annotation, something like aggregating annotations when I perform validation, i.e. I can combine @NotNull and @Size with (javax.validation.constraints) to the next annotation called "Name".

  package org.StudentLib.CustomeAnnotations; import@Target( {FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) @Retention(RUNTIME) @Constraint(validatedBy = {}) @Documented @NotNull @Id @Size(message = "The size of the name should be between {min} and {max} caracters", min = 1, max = 50, payload = Severity.Info.class ) public @interface Name { } 

So, how do I do the same for persistent annotations, I always get

@Id annotations are not allowed for this location

Why am I getting this error? Is there a way to combine save annotations and validation annotation in one annotation. The reason I ask about this is because there are about 40 tables (entities) in my code, and I feel that every time I need to determine the primary key of this table, I duplicate the code.

+6
source share
1 answer

You get this error because the Target meta annotation applied to the Id annotation type does not contain the ANNOTATION_TYPE parameters in its value field. Take a look at javadoc and you will see it ( ctrl + f '@Target').

@Target meta annotation describes which language java constructs annotation for. Because you cannot apply this annotation to ANNOTATION_TYPE , you cannot create such a label annotation.

As a side note, you can see by looking at this javadoc that @Target has @Target of {ANNOTATION_TYPE} , which actually makes the annotation a meta annotation.

0
source

All Articles