32

使用 JPA 注释,我想像这样重用相同的嵌入式对象:

@Entity
public class User {
    @Embedded
    public Address homeAddress;

    @Embedded
    public Address workAddress;
}

@Embeddable
public class Address {
    public String code;
    public String city;
    ...
} 

我可以用@AttributeOverrides、@AttributeOverride 和@Column 指定SQL 列名,但它是详细的。是否可以只为 homeAddress 和 workAddress 指定添加到每一列的前缀?

谢谢,

泽维尔

4

2 回答 2

12

如果您想使用多个相同Embedded的类。你必须@AttributeOverrides 为所有列做。尝试如下;

参考JPA AttributeOverrides

@Embeddable
public class Address {
    private String state;
    @Column(name = "zip_code")
    private String zip;
}

@Entity(name = "Employee")
public class Employee implements Serializable {
    @Embedded
    @AttributeOverrides({
        @AttributeOverride(name = "state", column = @Column(name = "province_1")),                       
        @AttributeOverride(name = "zip", column = @Column(name = "postal_code_2"))
    })
    private Address address_1;  

    @Embedded
    @AttributeOverrides({
        @AttributeOverride(name = "state", column = @Column(name = "province_2")),                       
        @AttributeOverride(name = "zip", column = @Column(name = "postal_code_2"))
    })
    private Address address_2;  

}   

我的建议是,如果Embedded您的Entity. 尝试使用@CollectionTable.

@CollectionTable(name = "EMPLOYEE_ADDRESS", joinColumns = @JoinColumn(name = "ADDRESS_ID"))
private List<Address> addressList;

参考JPA 集合表

于 2012-10-16T10:15:19.807 回答
3

添加这对我有用(虽然我使用休眠作为 JPA 提供程序)

<property name="hibernate.implicit_naming_strategy" value="org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl" />
于 2019-09-10T03:39:54.717 回答