使用Hibernate实现多表查询

项目中使用的是Hibernate框架,对于表查询一直只针对一张表,原码:

// 搜索员工
 public List searchUseraccount(String username, String deptid, String cid,
                                          String groupid) throws Exception {
     List accountList = new ArrayList();
     try {
              session = HibernateSessionFactory.getSession();
              t = session.beginTransaction();
              StringBuffer hql = new StringBuffer();
              hql.append("from Account where cid ='" + cid
                              + "' and username like '%" + username + "%'");
              if (null!=deptid&&!"0".equals(deptid)) {
                     hql.append(" and deptid='" + deptid + "'");
              }
              if (null!=groupid&&!"0".equals(groupid)) {
                     hql.append(" and gid='" + groupid + "'");
              }
              Query query = session.createQuery(hql.toString());
              accountList = query.list();
              t.commit();
     } catch (Exception e) {
              System.out.println("searchUseraccount fail!");
              e.printStackTrace();
     } finally {
              HibernateSessionFactory.closeSession();
     }
     return accountList;
 }

但需求变化--->表结构变化,查询的结果必须通过两张表,通过搜索(http://zjsoft.iteye.com/blog/152328)得到了解决办法,写法如下:

// 搜索员工
 public List searchUseraccount(String username, String deptid, String cid,
                                           String groupid) throws Exception {
     List accountList = new ArrayList();
     try {
             session = HibernateSessionFactory.getSession();
             t = session.beginTransaction();
             StringBuffer hql = new StringBuffer();
             hql.append("select * from account where cid ='" + cid
                             + "' and username like '%" + username + "%'");
             if (null != deptid && !"0".equals(deptid) && !"".equals(deptid)) {
                     hql.append(" and deptid='" + deptid + "'");
             }
             if (null != groupid && !"0".equals(groupid) && !"".equals(groupid)) {
                     hql.append(" and (aid in (select aid from Agmapping where "

                                     +" gid = '" + groupid + "')))");
             }
            Query query = session.createSQLQuery(hql.toString())

                                                       .addEntity(Account.class);
            accountList = query.list();
            t.commit();
     } catch (Exception e) {
            System.out.println("searchUseraccount fail!");
            e.printStackTrace();
     } finally {
            HibernateSessionFactory.closeSession();
     }
     return accountList;
 }

不同于我以前的写法在于红色区域,createSQLQuery方法的参数是纯sql语句,关于createSQLQuery的用法参见:http://jihongbin12329.iteye.com/blog/88678

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值