使用 getter/setter 与 HQL 查询?

Use getter/setter with HQL query?

我想直接使用 @Embedded 字段,使用包装 getter/setter 和 HQL sql 语句。

但是不行:

 org.hibernate.QueryException: could not resolve property: address.zip of: Customer [SELECT c FROM Customer c WHERE c.address.zip :=zip]

以下是否可行?

@Embeddable
pulic class ZipCode {
    String country;
    String zip;
}
@Embeddable
public class Address {
    String street;
    String town;

    @Embedded
    ZipCode zipCode;

    public String getZip() {
        return zipCode().getZip();
    }

    public void setZip(String zip) {
        zipCode.setZip(zip);
    }
}

@Entity
public class Customer {
    @Embedded
    Address address;
}

String FIND_BY_ZIP = "SELECT c FROM Customer c WHERE c.address.zip :=zip";

您可以将访问类型更改为 AccessType.PROPERTY

@Embeddable
public class Address {
    String street;
    String town;

    @Embedded
    @Access(AccessType.PROPERTY)
    ZipCode zipCode;

    public String getZipCode() {
        return zipCode().getZip();
    }

    public void setZipCode(String zip) {
        zipCode.setZip(zip);
    }
}

然后就可以做到

String FIND_BY_ZIP = "SELECT c FROM Customer c WHERE c.address.zipCode :=zip";

默认情况下,如果您将映射注释放在字段中,则属性的访问类型为 AccessType.FIELD(例如,您的 zipCode 中有 @Embedded)。

为了覆盖此默认行为,您可以使用 AccessType.PROPERTY 显式标记 属性,或者将 @Embedded 映射注释移动到 getZipCode() 方法.