JPA:如何覆盖@Embedded属性的列名

2022-09-01 06:36:39

Person

@Embeddable
public class Person {
    @Column
    public int code;

    //...
}

嵌入两个不同属性的两倍:和Eventmanageroperator

@Entity
public class Event {
    @Embedded
    @Column(name = "manager_code")
    public Person manager;

    @Embedded
    @Column(name = "operator_code")
    public Person operator;

    //...
}

在生成具有持久性的数据库架构时,这应该给出两个相应的列。相反,将引发异常:

org.hibernate.MappingException:实体映射中的重复列:事件列:代码

如何覆盖每个属性的默认列名代码


答案 1

使用@AttributeOverride,这是一个示例

@Embeddable public class Address {
    protected String street;
    protected String city;
    protected String state;
    @Embedded protected Zipcode zipcode;
}

@Embeddable public class Zipcode {
    protected String zip;
    protected String plusFour;
}

@Entity public class Customer {
    @Id protected Integer id;
    protected String name;
    @AttributeOverrides({
        @AttributeOverride(name="state",
                           column=@Column(name="ADDR_STATE")),
        @AttributeOverride(name="zipcode.zip",
                           column=@Column(name="ADDR_ZIP"))
    })
    @Embedded protected Address address;
    ...
}

在你的情况下,它看起来像这样

@Entity
public class Event {
    @Embedded
    @AttributeOverride(name="code", column=@Column(name="manager_code"))
    public Person manager;

    @Embedded
    @AttributeOverride(name="code", column=@Column(name="operator_code"))
    public Person operator;

    //...
}

答案 2

推荐