简体   繁体   English

JPA:创建自定义ID注释

[英]JPA: Create a custom ID annotation

I'm creating a new custom id annotation for the id fields of my entities: 我正在为实体的ID字段创建一个新的自定义ID注释:

@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 . 这似乎不起作用,因为它会出现此错误: 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). JPA没有这种元注释的概念(如错误消息所示)。

Note that this question has nothing to do with Spring, since all those annotations are JPA annotations, not Spring annotations. 注意,这个问题与Spring无关,因为所有这些注释都是JPA注释,而不是Spring注释。

Spring Boot does not provide implementation for this annotation. Spring Boot不提供此注释的实现。 This is responsibility of JPA implementation such as Hibernate. 这是JPA实施(例如Hibernate)的责任。 As I known, you cannot introduce new Id annotation for Hibernate. 众所周知,您不能为Hibernate引入新的Id注释。 Standard JPA annotations cannot be replaced because they are part of the standard. 标准JPA批注是标准的一部分,因此无法替换。 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. 您唯一可以做的-创建您的自定义子类,该子类将分配所需的ID,或实现一些Factory来创建具有分配的ID的Entity实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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