假设我将其命名为HQL(findRoomQuery):
select r from House h inner join h.roomList r
where h.address = :address and r.roomNo = :roomNo
House实体的映射如下:
<class name="com.example.House" table="house">
<id name="id" column="id" type="long">
<generator class="assigned" />
</id>
<property name="address" column="address" type="string" length="100" not-null="false"/>
<set name="roomList" cascade="none" lazy="false" fetch="join" inverse="true">
<key>
<column name="house_id"/>
</key>
<one-to-many class="com.example.Room"/>
</set>
</class>
虽然Room实体是这样的:
<class name="com.example.Room" table="room">
<id name="id" column="id" type="long">
<generator class="assigned" />
</id>
<property name="houseId" column="house_id" type="long" not-null="true"/>
<property name="roomNo" column="room_no" type="string" length="4" not-null="false"/>
</class>
关系是众议院可以有一个或多个房间。
执行查询的代码如下:
Query query = getSession().createQuery("findRoomQuery")
.setParameter("address", address)
.setParameter("roomNo", roomNo);
return query.list();
您可以从选择r (r是h.roomList的别名)中看到HQL返回会场实体。
如何使用Hibernate Criteria Query执行相同的操作? 有可能吗?
答案 0 :(得分:0)
试试这个
Criteria criteria = session.createCriteria(House.class, "house");
criteria.createAlias("house.roomList", "roomList");
criteria.add(Restrictions.eq("house.address",address));
criteria.add(Restrictions.eq("roomList.roomNo", roomNo));
criteria.setProjection(Projections.property("roomList"));
Room r = (Room) criteria.uniqueResult();
替换
<property name="houseId" column="house_id" type="long" not-null="true"/>
到
<many-to-one name="houseId" class="com.example.House" fetch="select">
<column name="house_id" not-null="true" />
</many-to-one>