简体   繁体   中英

JPA: Create a custom ID annotation

I'm creating a new custom id annotation for the id fields of my entities:

@Id
@GeneratedValue(generator = RandomAlphanumericIdGenerator.generatorName)
@GenericGenerator(name = RandomAlphanumericIdGenerator.generatorName, strategy = "com.boot.myproject.utils.RandomAlphanumericIdGenerator")
private String id;

It works fine. But I want to group all these three annotations under one new annotation:

@Id
@GeneratedValue(generator = RandomAlphanumericIdGenerator.generatorName)
@GenericGenerator(name = RandomAlphanumericIdGenerator.generatorName, strategy = "com.boot.myproject.utils.RandomAlphanumericIdGenerator")
@Target({FIELD})
@Retention(RUNTIME)
public @interface RandomAlphanumericId {

}

Which doesn't seem to work, as it gives this error: The annotation @Id is disallowed for this location .

I'd like to know if it is possible to group these annotations under one.

No, it's not possible. JPA doesn't have this notion of meta-annotation (as the error message indicates).

Note that this question has nothing to do with Spring, since all those annotations are JPA annotations, not Spring annotations.

Spring Boot does not provide implementation for this annotation. This is responsibility of JPA implementation such as Hibernate. As I known, you cannot introduce new Id annotation for Hibernate. Standard JPA annotations cannot be replaced because they are part of the standard. The only thing you could do - create your custom subclass which will assign required Id or implement some Factory that will create Entity instances with assigned id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM