Hibernate使用sql语句实现多表关联查询
/** * <查找list> * * @return 返回页面需要显示的数据 */ @SuppressWarnings("unchecked") public List<Map<String, String>> findUserDept() { return ht.executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { String sql = "SELECT u.username name,u.password p,d.name deptName " + "FROM usertable u LEFT JOIN depttable d ON u.dept_id=d.id"; Query query = session.createSQLQuery(sql) .addScalar("name", Hibernate.STRING) .addScalar("p", Hibernate.STRING) .addScalar("deptName", Hibernate.STRING) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);//返回List<Map>其中map的key就是我们定义的别名 return query.list(); } });
测试代码
List<Map<String, String>> listUserDept = userService.findUserDept(); // 循环 for (Map<String, String> map : listUserDept) { System.out.println(map.get("name"));//key是我们写sql语句的别名 System.out.println(map.get("p")); System.out.println(map.get("deptName")); System.out.println("---------------------------------"); } }