Arian
Arian

Reputation: 7719

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.

Upvotes: 0

Views: 672

Answers (2)

jreznot
jreznot

Reputation: 2773

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.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691765

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.

Upvotes: 2

Related Questions