问题描述
- 动态sql实现模糊查询错误
-
public List findByCondition(String readerTypeId, String barcode,
String name, final int page, final int pageSize)
throws DAOException {
final List params = new ArrayList();
final String hql = createFindHQL(readerTypeId, barcode, name, params, page,
pageSize);
List list = (List) super.getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(hql);
// 分页参数
int begin = (page - 1) * pageSize;
query.setFirstResult(begin);
query.setMaxResults(pageSize);
for (int i = 0; i < params.size(); i++) {
query.setParameter(i, params.get(i));
}
return query.list();
}
});
// 将list集合封装成List
List readerList = new ArrayList();
for (Object[] objs : list) {
ReaderVO vo = new ReaderVO();
Reader r = (Reader)objs[0];
//将r属性值给vo属性赋值
BeanUtils.copyProperties(r, vo);
vo.setReaderTypeName(objs[1].toString());
readerList.add(vo);
}
return readerList;
}private String createFindHQL(String readerTypeId, String barcode, String name, List<Object> params, int page, int pageSize) { // 开始拼子查询 StringBuffer sb = new StringBuffer(); sb.append("select a,b.typeName "); sb.append("from Reader a,ReaderType b "); sb.append("where a.readerType = b.id "); if (readerTypeId != null && readerTypeId.length() > 0) { sb.append("and a.readerType=? "); params.add(readerTypeId); } if(barcode != null && barcode.length() > 0){ sb.append("and a.barcode=? "); params.add(barcode); } if (name != null && name.length() > 0) { sb.append("and a.name like ? "); params.add("'%" + name + "%'"); } sb.append("order by a.id"); System.out.println(sb.toString()); return sb.toString(); }
我JUnit方法:List list = readerDao.findByCondition("4", null, "om", 1, 5);
数据库中有name为"tom"的记录,但是没找到。
为什么?
时间: 2024-10-31 12:48:01