JPA 多个带前缀的嵌入式字段?

2022-09-01 07:52:07

对于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 列名,但它是 verbos。是否可以只指定一个前缀以添加到主地址和工作地址的每个列中?

谢谢

泽维尔


答案 1

如果要使用多个相同的类。您必须对所有列执行操作。请尝试如下;Embedded@AttributeOverrides

引用 JPA 属性覆盖

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

}   

我的建议,如果你的.尝试使用 。EmbeddedEntity@CollectionTable

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

参考 JPA 集合表


答案 2

添加这个对我有用(我正在使用休眠作为JPA提供程序)

<property name="hibernate.implicit_naming_strategy" value="org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl" />

推荐