使用带有HQL查询的getter / setter?

时间:2015-02-20 08:47:44

标签: java hibernate hql

我想直接使用带有@Embedded sql语句的包装getter / setter来使用HQL字段。

但它不起作用:

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

1 个答案:

答案 0 :(得分:4)

您可以将访问类型更改为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(例如,您@Embedded中有zipCode)。

要覆盖此默认行为,您可以使用AccessType.PROPERTY明确标记属性,或将@Embedded映射批注移至getZipCode()方法。