首页 > 代码库 > hibernate的三表查询

hibernate的三表查询

表的关系:

Cardgraderule      1:n     Cardgrade

Cardgrade           1:n     Acardtype

实体类:

public class Cardgraderule implements java.io.Serializable {    private Cardgrade cardgrade;        ......}public class Cardgrade implements java.io.Serializable {    private Acardtype cardtype;        ......

1.通过Criteria查询实现三表查询

封装的dao方法:

public class BaseDAOHibernate extends HibernateDaoSupport{    public List findAllByCriteria(final DetachedCriteria detachedCriteria)  throws DataAccessException  {                return (List)getHibernateTemplate().execute(new HibernateCallback() {                     public Object doInHibernate(Session session)  throws HibernateException  {                        Criteria criteria = detachedCriteria.getExecutableCriteria(session);                        return criteria.list();                    }                }        , true);     }}  

 

业务方法:

     DetachedCriteria cardy2 = DetachedCriteria.forClass(Cardgraderule.class, "cardgraderule");     cardy2.createAlias("cardgrade","g")                .add(Restrictions.eq("g.cardtype.agentid", agenttbl.getAgentid()));     List list = commonDao.findAllByCriteria(cardy2);

下图是listCardgrade的封装规格:  可以看到返回的是  Cardgraderule

技术分享 

2.通过hql实现三表查询

封装的dao方法:

public class BaseDAOHibernate extends HibernateDaoSupport{          public List find(String query)  throws DataAccessException {                return getHibernateTemplate().find(query);    }}    

业务方法:

 String hql = "select distinct c from Cardgraderule c left join fetch c.cardgrade  g  left join fetch g.cardtype"; List find = commonDao.find(hql);

结果的封装:

技术分享

 

hibernate的三表查询