Hibernate 多对一 left join
hibernate的hql是一种中立的数据库查询语言,会随着本地配置的方言选项,进行sql的翻译。
User.hbm.xml
<hibernate-mapping package="com.crm.">
<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.crm">
<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";
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());
}