CREATE TABLE EMPLOYEE (
EMP_ID INTEGER(5) PRIMARY KEY DEFAULT 1,
EMP_NAME VARCHAR(30) NOT NULL
);
CREATE TABLE PHONENUMBER (
PH_NUMBER VARCHAR(10) NOT NULL,
PH_NUMBER_TYPE VARCHAR(10),
EMP_ID INTEGER(5) NOT NULL,
FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (EMP_ID)
);
我有两个类Employee作为实体类
public class Employee{
private int empId;
private String empName;
private Set<PhoneNumber>phNoSet;
}
和PhoneNumber作为值类
public class PhoneNumber{
private String phoneNo;
private String phNoType;
}
下面是hibernate中Employee和PhoneNumber之间的xml映射。
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the portal detail.
</meta>
<id name="empi\Id" type="string">
<column name="emp_id" sql-type="char(32)"/>
<generator class="uuid"/>
</id>
<property name="empName" column="emp_name" type="string" not-null="true"/>
<set name="phNoSet" table="PHONENUMBER">
<key column="empId"/>
<composite-element class="PortalL10n">
<property name="phoneNo" column="ph_number" type="string" not-null="true"/>
<property name="phNoType" column="ph_nmber_type" type="string" not-null="true" />
</composite-element>
</set>
</class>
</hibernate-mapping>
当我使用emp_id ='101'访问员工时使用休眠。我从PHONENUMBER表中获取所有条目。但我只需要来自PHONENUMBER表的条目,其中ph_number_type ='住宅'用于emp_id ='101'的员工。
我尝试了以下方法,但没有成功。
List results = session.createCriteria(Employee.class)
.add( Restrictions.eq("empId", 101) )
.createCriteria("phNoSet")
.add( Restrictions.eq("phNoType", "residential") )
.list();
我怎样才能实现它?
答案 0 :(得分:0)
这就足够了:
List results = session.createCriteria(Employee.class)
.add( Restrictions.eq("empId", 101) )
.add( Restrictions.eq("phNoSet.phNoType", "residential") )
.list();
或
List results = session.createCriteria(Employee.class)
.add( Restrictions.eq("empId", 101) )
.createAlias("phNoSet", "p")
.add( Restrictions.eq("p.phNoType", "residential") )
.list();