使用Hibernate实现多表查询
程序员文章站
2022-04-15 23:00:51
...
项目中使用的是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.javaeye.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.javaeye.com/blog/88678
上一篇: JS中响应函数和for循环执行问题
下一篇: Ubuntu adb 报错:no permissions (user in plugdev group; are your udev rules wrong?);
推荐阅读
-
使用python脚本实现查询火车票工具
-
hibernate 命名查询如何实现
-
教你使用mongoose实现多集合关联查询
-
PHP+MySQL使用mysql_num_rows实现模糊查询图书信息功能
-
使用Java实现数据库编程—03 第三章 高级查询(一)
-
hibernate使用HibernateCallback回调的方法查询SQL时couldnotexecutequery--作怪的别名
-
MyBatis从入门到精通(十):使用association标签实现嵌套查询
-
使用fastapi完成一个车辆违章查询,可以看到实现页面
-
SQL语句实现查询Index使用状况
-
SQL语句实现查询SQL Server内存使用状况