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

Ole*_*lov 20 java orm hibernate jpa

Person

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

    //...
}
Run Code Online (Sandbox Code Playgroud)

嵌入Event两次作为两个不同的属性:manageroperator

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

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

    //...
}
Run Code Online (Sandbox Code Playgroud)

在使用Persistence生成数据库模式时,这应该给出两个相应的列.而是抛出异常:

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

如何覆盖code每个属性的默认列名?

Pre*_*ric 43

使用@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;
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

@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;

    //...
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为没有必要写`@AttributeOverrides`。这也可以直接写入所有“@AttributeOverride”。 (4认同)