一级级联到处都是,直接上2级级联吧。
三个表,user,grade,school。
学生关联年级,年级关联学校。现在我想查出user的同时知道他所在的班级和学校!
User.hbm.xml
<hibernate-mapping>
<class name="com.supben.pojo.User" table="User">
<id name="userId" type="java.lang.Long">
<column length="20" name="userId" />
<generator class="identity"></generator>
</id>
<property name="userName" type="java.lang.String">
<column name="userName" />
</property>
<many-to-one name="grade" column="gradeId" class="com.supben.pojo.Grade" />
</class>
</hibernate-mapping>
Grade.hbm.xml
<hibernate-mapping>
<class name="com.supben.pojo.Grade" table="grade">
<id name="gradeId" type="java.lang.Integer">
<column length="20" name="gradeId"/>
<generator class="identity"></generator>
</id>
<property name="gradeName" type="java.lang.String">
<column name="gradeName"/>
</property>
<many-to-one name="school" column="schoolId" class="com.supben.pojo.School"/>
</class>
</hibernate-mapping>
School.hbm.xml
<hibernate-mapping>
<class name="com.supben.pojo.School" table="school">
<id name="schoolId" type="java.lang.Integer">
<column length="20" name="schoolId"/>
<generator class="identity"></generator>
</id>
<property name="schoolName" type="java.lang.String">
<column name="schoolName"/>
</property>
</class>
</hibernate-mapping>
qbc查询方法
@SuppressWarnings("unchecked")
public List<User> find3Table() {
Criteria c = userDao.createCriteria();
//添加user表的查询字段
c.add(Restrictions.eq("userName", "supben"));
//添加grade表的关联,并指定别名为grade
c.createAlias("grade","grade");
//添加grade表查询字段
c.add(Restrictions.eq("grade.gradeName", "101"));
//添加schoo表的关联,并指定别名为school
c.createAlias("grade.school","school");
//添加school表的查询字段
c.add(Restrictions.eq("school.schoolName", "宿松中学"));
//添加user表和school表互相关联的条件
c.add(Restrictions.eqProperty("userId", "school.schoolId"));
return c.list();
}
}
测试方法
public void testQBC(){
List<User> userList = userService.find3Table();
for (User user : userList){
System.out.println("姓名: "+user.getUserName());
System.out.println("班级: "+user.getGrade().getGradeName());
System.out.println("学校: "+user.getGrade().getSchool().getSchoolName());
}
说明:如果不涉及到从表中的字段的话,其实还有一种更简单的方法
@SuppressWarnings("unchecked")
public List<User> find3Table() {
Criteria c = userDao.createCriteria();
//立即用join的方法加载grade
c.setFetchMode("grade", FetchMode.JOIN);
//立即用join的方式加载school
c.setFetchMode("grade.school", FetchMode.JOIN);
//user表中的查询字段
c.add(Restrictions.eq("userName", "supben"));
return c.list();
}
问题的关键在哪:这样你添加不了班级表的条件来构建查询,类似于
c.add(Restrictions.eq("grade.gradeName", "101"));
一直报错说,无法解析user的grade.gradeName属性,必须要起别名!
或者是我没有找到,欢迎高手指教