第一种方式:QBC查询
String name = "", info = "";
if (sub != null && sub.getSubname() != null) {
name = sub.getSubname();
}
if (sub != null && sub.getSubinfo() != null) {
info = sub.getSubinfo();
}
Criteria cr = session.createCriteria(Subject.class);
cr.add(Expression.like("subname","%"+name+"%"));
cr.add(Expression.like("subinfo","%"+info+"%"));
第二种方式:HQL查询语句
String hql = "from Subject as s where s.subname like :name and s.subinfo like :info";
// 调用session的获得数据列表方法,传递HQL查询语句
Query query = session.createQuery(hql);
query.setString("name","%"+name+"%");
query.setString("info","%"+info+"%");
System.out.println("*********"+hql);
第三种方式:HQL查询语句(查询条件只能为英文或数字,汉字在传递到hibernate内部时出现乱码问题)
String hql = "from Subject as s where s.subname like '%"+name+"%' and s.subinfo like '%"+info+"%'";//调用session的获得数据列表方法,传递HQL查询语句
Query query = session.createQuery(hql);
注:Subject为数据库表subject映射的类;它有相应的属性subname、subinfo及相应的get和set方法;sub为Subject的一个实例化对象。