jpa @AttributeOverrides在spring Boot 项目中不起作用

carvr3hs  于 2023-10-19  发布在  Spring
关注(0)|答案(1)|浏览(151)

我有一个可嵌入的类。问题是,我想通过@AttributeOverrides覆盖它的属性,但它并不像我期望的那样工作

@Embeddable
@Data
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Address {
    @NotNull
    @NotBlank
    @Column(name = "CITY")
    private String city;

    @NotNull
    @NotBlank
    @Column(name = "ZIP_CODE")
    private String zipCode;

    @NotNull
    @NotBlank
    @Column(name = "STREET")
    private String street;

    @NotNull
    @NotBlank
    @Column(name = "COUNTRY")
    private String country;

    @Override
    public String toString() {
        return String.format("%s, %s, %s, %s", country, city, street, zipCode);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Address)) return false;
        Address address = (Address) o;
        return city.equals(address.city) && zipCode.equals(address.zipCode) && street.equals(address.street)
                && country.equals(address.country);
    }

    @Override
    public int hashCode() {
        return Objects.hash(city, zipCode, street, country);
    }
}

在我的实体类中有这个字段的定义

@Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "CITY",
                column = @Column(name = "COMPANY_BRANCH_CITY")),
            @AttributeOverride(name = "zip_code",
                column = @Column(name = "COMPANY_BRANCH_ZIP_CODE")),
            @AttributeOverride(name = "STREET",
                column = @Column(name = "COMPANY_BRANCH_STREET")),
            @AttributeOverride(name = "COUNTRY",
            column = @Column(name = "COMPANY_BRANCH_COUNTRY"))
    })
    private Address companyBranchAddress;

当hibernate生成我的schema时,它是错误的,属性名称来自可嵌入的类,它们没有改变:

Hibernate: 
    create table company_branch (
        id bigint generated by default as identity,
        company_branch_budget varchar(63) not null,
        city varchar(255),
        company_branch_phone_number varchar(255) not null,
        country varchar(255),
        street varchar(255),
        zip_code varchar(255),
        primary key (id)
    )

我错过了什么?

g6ll5ycj

g6ll5ycj1#

这是因为@AttributeOverridename应该引用@Embeddable类的字段名称,而不是数据库列名。此外,它是大小写敏感的。
因此,更改为以下内容应该可以解决问题:

@Embedded
@AttributeOverrides({
        @AttributeOverride(name = "city",column = @Column(name = "COMPANY_BRANCH_CITY")),
        @AttributeOverride(name = "zipCode",column = @Column(name = "COMPANY_BRANCH_ZIP_CODE")),
        @AttributeOverride(name = "street",column = @Column(name = "COMPANY_BRANCH_STREET")),
        @AttributeOverride(name = "country",column = @Column(name = "COMPANY_BRANCH_COUNTRY"))
})
private Address companyBranchAddress;

相关问题