如何组合hibernate映射的注释?

时间:2017-07-21 14:15:17

标签: java jpa annotations

假设(使用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

2 个答案:

答案 0 :(得分:1)

作为Neil Stockton mention,元注释可能是下一个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克服这种冗长。

答案 1 :(得分:0)

理论上它应该是这样的:

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