部分代码如下:
public List<FarmMes> findAll(String name,String loc,String date1,
String date2, int currentPage,int lineSize) throws Exception {
// TODO Auto-generated method stub
String hql = "from FarmMes as farm where farm.farmName like :name or farm.location like :loca or " +
"farm.registDate between :date1 and :date2";
Query query = sess.createQuery(hql).setString("name", "%" + name + "%").setString("loca", "%" + loc + "%").
setString("date1", date1).setString("date2", date2); //分页查询
page = query.list().size();
query.setFirstResult((currentPage - 1 ) * lineSize);
query.setMaxResults(lineSize);
List<FarmMes> list = query.list();
return list;
}
测试代码:
@Test
public void testSome() {
try {
List<FarmMes> list = dao.findAll("", "广东省深圳龙岗区1", "2015-05-01", "2015-05-06", 1, 11);
System.out.println(list.size());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
得出的结果是把数据库中的数据全部返回了,并没有按照条件那样得出"2015-05-01", "2015-05-06"这个范围内的数据,然后当我把hql语句改成“from FarmMes as farm where farm.location like :loc” 这样之后,去查location进行模糊+分页就可以得出结果,当模糊查询的条件加到2个以上的时候就无法得出正确的结果(例如:from FarmMes as farm where farm.farmName like :name or farm.location like :loca,hql变成这样之后结果又不正确了。)请问这是什么原因,有什么方法改?
------解决思路----------------------
setString("name", "%" + name + "%") 改成setString("name", " '%" + name + "%' ") 试试,就是在%前后加个单引号
------解决思路----------------------
楼上整解 ,
不过还提供一种方式,使用Example方式
Example studentExample = Example.create(student).enableLike(MatchMode.ANYWHERE).excludeNone().ignoreCase() ;