HQL查询
通过Criteria查询
//查询列表
public List<Student> getInfo(Student student) {
Criteria criteria = getSession().createCriteria(Student.class);
if (StringUtil.isNotEmpty(Student.getAge())) {
criteria.add(Restrictions.eq("age",Student.getAge()));
}
return criteria.list();
}
通过原生的sql查询
//返回一个实例
public String getInfo(Student student) {
StringBuffer sqlBuffer = new StringBuffer("select count(*) from student where 1=1");
if (StringUtil.isNotEmpty(student.getName())) {
sqlBuffer.append(" and name=:name");
}
SQLQuery sqlQuery = getSession().createSQLQuery(sqlBuffer.toString());
if (StringUtil.isNotEmpty(student.getName())) {
sqlQuery.setParameter("name", student.getName());
}
return (String) sqlQuery.uniqueResult();
}
//查询多个数据
public List<Student> getInfo(Student student) {
StringBuffer sqlBuffer = new StringBuffer("select name,age from student where 1=1");
if (StringUtil.isNotEmpty(student.getName())) {
sqlBuffer.append(" and name=:name");
}
if (StringUtil.isNotEmpty(student.getAge())) {
sqlBuffer.append(" and age=:age");
}
SQLQuery sqlQuery = getSession().createSQLQuery(sqlBuffer.toString());
if (StringUtil.isNotEmpty(student.getName())) {
sqlQuery.setParameter("name", student.getName());
}
if (StringUtil.isNotEmpty(student.getAge())) {
sqlQuery.setParameter("age", student.getAge());
}
//将查询结果映射为Student类/对象/bean
return sqlQuery.setResultTransformer(Transformers.aliasToBean(Student.class));
//或声明更实体 return sqlQuery.addEntity(Student.class);
}
Criteria查询条件
eq() 等值查询
ge() 大于等于
gt() 大于
le() 小于等于
lt() 小于
between() 大于小的且小于大的
like() 模糊查询
like().ignoreCase() 不区分大小写模糊查询
ilike() 规则模糊查询
or() 或查询
isNotNull() 非空
isNUll() 为空
isNotEmpty() 存在
isEmpty() 不存在
可参考链接:https://docs.jboss.org/hibernate/orm/3.5/reference/zh-CN/html/querycriteria.html