两表关联
TBorrow表和TUser表关联ID查询,依据 <many-to-one name="TUserByAdminId" class="com.shop.model.TUser" fetch="select">
- DetachedCriteria criteria = DetachedCriteria.forClass(TBorrow.class);
- criteria.add(Restrictions.eq("TUserByBorrowPeopleId.id", user));
- getHibernateTemplate().findByCriteria(criteria)或criteria.list()
以上测试通过!
三表关联
如果一次类推, 依据 <many-to-one name="TBookOfBorrow" class="com.shop.model.TBook" fetch="select">
<many-to-one name="TBaserefByBookGrade" class="com.shop.model.TBaseref" fetch="select">
一次类推
- DetachedCriteria criteria = DetachedCriteria.forClass(TBorrow.class);
- criteria.add(Restrictions.eq("TBookOfBorrow.TBaserefByBookCategory.id", user));
- getHibernateTemplate().findByCriteria(criteria)或criteria.list()
执行出错,可见Restrictions无法三表分析,通过测试得到,Restrictions仅仅只能得到关联表的ID值,英雌为了实现三表查询,改进查询语句,得到如下代码
- DetachedCriteria criteria = DetachedCriteria.forClass(TBorrow.class);
- Session session=getSession();
- List<Integer> list=new ArrayList<Integer>();
- List<TBook> tBooks=session.createCriteria(TBook.class).add(Restrictions.eq("TBaserefByBookCategory.id", category)).list();
- list.add(tBooks.get(i).getId());
- criteria.add(Restrictions.in("TBookOfBorrow.id",list));
- getHibernateTemplate().findByCriteria(criteria)或criteria.list()
拆分标的查询成功执行,得到所需的结果。2013/7/29 0:04
今天早上通过上网浏览和查找API,终于找到了更简单的方法,在此记下来
Alias 别名
criteria的子查询考这个来完成。包括
LEFT_JOIN,INNER_JOIN,FULL_JOIN
所以以上想实现TBookOfBorrow.TBaserefByBookCategory.id只要给其中的一个去一个别名就行
如
TBookOfBorrow --> t
t.TBaserefByBookCategory.id
这样就行了
同样,通过表的其他字段来查询也需要这个方式
上面代码改成:
- DetachedCriteria criteria = DetachedCriteria.forClass(TBorrow.class);
- criteria.createAlias("TBookOfBorrow", "t");
- criteria.add(Restrictions.eq("t.TBaserefByBookCategory.id", category));
- getHibernateTemplate().findByCriteria(criteria)或criteria.list()