最近刚接触hibernate,今天笔者就hibernate查询的几个方法做简单阐述。
getHibernateTemplate().find(sql)和 session.createSQLQuery(hql).list()
- ----------------------------------return getHibernateTemplate().find(hql):返回一个查询的结果集,一般是一个实体类的list。
2.--------------------------------------Session session = getCurrentSeesionBySelf();
return session.createSQLQuery(hql).list();
session.close(); 同样也是返回一个List,但是结果是一个Object 类型的list ,.
下面我想谈谈1和2到底在使用过程中有什么要特别注意的地方:
我们知道1中的方法是hibernate框架中很方便的方法,比如,sql语句可以这样写:
sql = "from User(实体类) where name='张三' ";
而2中的则有些不同:
sql = " select * from user(表名) where name like '%张%' and sex='男' group by name order by sex";
比较发现:1比较适合简单的sql语句,并且from后面是一个实体类,需要进行映射。
2适合复杂的sql语句 ,from后面是数据库真实的表名。
3.这是我修改后的dao层代码:
public List<Object[]> daysDetectList(String time, String path) throws SQLException {
Session session = getCurrentSeesionBySelf();
path = "%" + path + "%";
String sql = "select count(distinct clientMac),timeStamp from presence as p where path like '" + path + "'and timeStamp like '" + time + "%' and clientType='Uncategorized Device' GROUP BY DATE_FORMAT('timeStamp','%y-%m-%d') order by timeStamp asc" ;
List<Object[]> list = session.createSQLQuery(sql).list();
session.close();
return list;
}
Session session = getCurrentSeesionBySelf();
path = "%" + path + "%";
String sql = "select count(distinct clientMac),timeStamp from presence as p where path like '" + path + "'and timeStamp like '" + time + "%' and clientType='Uncategorized Device' GROUP BY DATE_FORMAT('timeStamp','%y-%m-%d') order by timeStamp asc" ;
List<Object[]> list = session.createSQLQuery(sql).list();
session.close();
return list;
}
4.这是我修改前的dao层代码:
public List<Object[]> daysDetectList(String time, String path) throws SQLException {
path = "%" + path + "%";
String hql = "select count(distinct clientMac),timeStamp from PresenceEntity as p where path like '" + path + "'and timeStamp like '" + time + "%' and clientType='Uncategorized Device' GROUP BY DATE_FORMAT('timeStamp','%y-%m-%d') order by timeStamp asc" ;
return getHibernateTemplate().find(hql);
}
path = "%" + path + "%";
String hql = "select count(distinct clientMac),timeStamp from PresenceEntity as p where path like '" + path + "'and timeStamp like '" + time + "%' and clientType='Uncategorized Device' GROUP BY DATE_FORMAT('timeStamp','%y-%m-%d') order by timeStamp asc" ;
return getHibernateTemplate().find(hql);
}
4中的代码我在mysql中执行sql语句搜出2条记录,可是返回的list一直都是一条,另一条总是不显示。几经周折,我改成了3的版本,list的值则可以成功取得,
原因在于:4中适合简单的sql语句的执行,一旦sql语句较为复杂,最好使用3中原始的sql语句,别要使用hql,否则会造成框架的不识别和数据的丢失。