【转】Hibernate left join(左连接)
如果是内连接的多表查询可以不用join关键字,在where里面关联,与sql一样,如:
" select ehrtonc from EHRTONCPO ehrtonc , NCTOEHRPO nctoehr where nctoehr.ffgcid = :payprocessid and nctoehr.hroid = ehrtonc.oid"
Hibernate left join一直是困扰我的一个问题,因为对hibernate的关联映射不怎么了解,写的Hql也全部是从sql翻译过来,虽然也是大同小异,但是left join 和join总报错Path expected for join!。所以一直是不用join关键字进行关联,但是遇到left join就只能用sql写了,影响效率。
其实很简单:
1、先把关联映射配好(必须配置好关联关系才能在sql中用join关键字)
User.hbm.xml
<hibernate-mapping package="com.xieqing.crm.user">
<class name="User" table="tbl_user">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="truename" not-null="true" column="truename" length="32"/>
<property name="sex" column="sex" length="1"/>
<property name="phone" column="phone"/>
<property name="roomId" column="room_id" not-null="false"/>
<many-to-one name="room" class="com.xieqing.crm.room.Room" column="room_id"
insert="false" update="false"/>
</class>
</hibernate-mapping>
Room.hbm.xml
<hibernate-mapping package="com.xieqing.crm.room">
<class name="Room" table="tbl_room">
<id name="id" column="room_id">
<generator class="native"></generator>
</id>
<property name="roomName" not-null="true" column="room_name" length="32"/>
<set name="users">
<key column="room_id"></key>
<one-to-many class="com.xieqing.crm.user.User" not-found="ignore"/>
</set>
</class>
</hibernate-mapping>
User.java
public class User{
private Integer id;
private String truename;
private String phone;
private int sex;
private Integer roomId;
private Room room;
// 省略Getter setter方法
}
Room.java
public class Room {
private Integer id;
private String roomName;
private Set<User> users;
// 省略Getter setter方法
}
tbl_user 表
tbl_room 表
// 注意:这里连接的就是User.java里的room属性了, 改了这里就OK啦。如果后面要加条件就
用with (SQL是用的on)
String hql = "select u from User u left join u.room";(关联哪个列就得xml里面配置关联)
List<User> userList = this.getHibernateTemplate().find(hql).list();
System.out.println("size----"+userList.size());
for(User u : userList) {
System.out.println(u.getId() + " --- " + u.getTruename());
}
执行该查询将把tbl_user表中的4个人都查出来。