访问hibernate中的组件属性

时间:2014-02-25 14:22:43

标签: java hibernate hibernate-mapping hibernate-criteria

我有三节课 Student.java

public class Student {
    long id;
    String name;
    Address address;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
}

Address.java

public class Address {
    String houseNumber;
    String addrLine1;
    String addrLine2;
    String phone;

    public String getHouseNumber() {
        return houseNumber;
    }
    public void setHouseNumber(String houseNumber) {
        this.houseNumber = houseNumber;
    }
    public String getAddrLine1() {
        return addrLine1;
    }
    public void setAddrLine1(String addrLine1) {
        this.addrLine1 = addrLine1;
    }
    public String getAddrLine2() {
        return addrLine2;
    }
    public void setAddrLine2(String addrLine2) {
        this.addrLine2 = addrLine2;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
}

Student.hbm.xml的Hibernate Mapping Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Student" table="STUDENT">
<id name="id" type="long" column="ID"/>
  <property name="name" column="NAME"/>
  <component name="address" class="Address">
    <property name="houseNumber" column="HOUSE_NUMBER" not-null="true"/>
    <property name="addrLine1" column="ADDRLINE1"/>
    <property name="addrLine2" column="ADDRLINE2"/>
    <property name="phone" column="PHONE"/>
  </component>
</component>
</class>
</hibernate-mapping>

现在我想使用分离标准访问属性houseNumber,phone 但当我试图把财产作为地址。电话
我把错误视为
org.hibernate.QueryException:无法解析属性:phone of:Student

1 个答案:

答案 0 :(得分:0)

发生错误是因为学生确实没有“电话”,这是一个地址属性。

对于常见标准,正确的用法应该是session.createCriteria( Student.class ).add( Restrictions.eq( "address.phone", "myPhoneNumber" ) ).list()

DetachedCriteria的版本是

DetachedCriteria criteria = DetachedCriteria.forClass( Student.class ).add(Restrictions.eq( "address.phone", "99999999" ) );
List students = criteria.getExecutableCriteria( session ).list();