【问题标题】:How to combine annotations for hibernate mapping?如何结合注解进行休眠映射?
【发布时间】:2017-07-21 14:15:16
【问题描述】:

假设(使用JPA)我有一个带有 id 的实体:

...
@Id
@TableGenerator(name = "EVENT_GEN",
                table = "SEQUENCES",
                pkColumnName = "SEQ_NAME",
                valueColumnName = "SEQ_NUMBER",
                pkColumnValue = "ID_SEQUENCE",
                allocationSize=1)
private Long id;
...

我怎样才能声明一个自定义注解,所以上面的 id 映射将是:

@CustomIdAnnotation
private Long id

可能是这样的SO answer

【问题讨论】:

标签: java jpa annotations


【解决方案1】:

作为Neil Stocktonmention,元注释可能是下一个JPA 2.2版的part

现在,使用 JPA 2.1,我可以将 @Embeddable 类用于 id (@EmbeddedId) 和非 id 字段 (@Embedded)

请注意,对于 @Embeddable,我可以使用泛型类,因此它对任何类型都很有用 + 我可以轻松覆盖我的列属性:

@Embeddable
@Getter @Setter @NoArgsConstructor // Lombok library
public class EmbeddableGeneric<T> {
    @Column 
    // other annotations
    T myField;
    
    ...
}

在我的实体类中:

@Entity
@Getter @Setter @NoArgsConstructor // You know now what's this!
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    @Embedded
    @AttributeOverride(name = "myField", column = @Column(name = "STRING_FIELD"))
    private EmbeddableGeneric<String> myString;

...
}

让我们等待 JPA 2.2 克服这种冗长。

【讨论】:

  • 此处的 GitHub 问题链接已过时。 Java EE 已被弃用,Eclipse 基金会已承担了推进其项目和规范的任务,作为EE4J 的一部分。这是跟踪此问题进度的新位置:github.com/eclipse-ee4j/jpa-api/issues/43
【解决方案2】:

理论上应该是这样的:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.persistence.Id;
import javax.persistence.TableGenerator;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomIdAnnotation {

    TableGenerator generator() default @TableGenerator(name = "EVENT_GEN", 
            table = "SEQUENCES", 
            pkColumnName = "SEQ_NAME", 
            valueColumnName = "SEQ_NUMBER", 
            pkColumnValue = "ID_SEQUENCE", 
            allocationSize = 1);

    Id id();
}

但是,我认为这不起作用,因为持久性提供程序(Hibernate、EclipseLink 等)直接在您的实体类中处理包javax.persistence.* + 提供程序特定注释的注释。因此,如果您打算编写自己的持久性提供程序,这可能会起作用。 (implementing JSR-000338 JPA 2.1 specification)

【讨论】:

  • 我不认为将您的 id 放在您的自定义注释中是一个好主意,这个想法是将我的冗长和重复的 JPA 注释分组到一个单独的注释中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多