2 dongzuomianban dongzuomianban 于 2014.02.22 00:40 提问

动态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"的记录,但是没找到。
为什么?

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!