第一种,适合sql语言水平比较高的人用
HQL(Hibernate Query Language)
面向对象的查询语言,与SQL不同,HQL中的对象名是区分大小写的(除了JAVA类和属性其他部分不区分大小写);HQL中查的是对象而不是和表,并且支持多态;HQL主要通过Query来操作,Query的创建方式:
Query q = session.createQuery(hql);
eg: from Person
from User user where user.name=:name
from User user where user.name=:name and user.birthday < :birthday
1 @SuppressWarnings("unchecked") 2 @Override 3 @Transactional(propagation = Propagation.NOT_SUPPORTED) 4 public List<User> check(String username, String email, String peopleId) { 5 String hql = "from User where username=:uName or email=:email or peopleId=:PID"; 6 Query q = factory.getCurrentSession().createQuery(hql); 7 q.setString("uName", username); 8 q.setString("email", email); 9 q.setString("PID", peopleId); 10 List list = q.list(); 11 return list; 12 }
第二种,矮油,偶sql语言水平有点欠缺,用这个吧,""内是表格的字段名,这里千万要注意,字段名要和hbm.xml文件中字段名大小写一致。
Criteria
Criteria是一种比HQL更面向对象的查询方式;Criteria的创建方式:
Criteria crit = session.createCriteria(DomainClass.class);
简单属性条件如:criteria.add(Restrictions.eq(propertyName, value)), 这个Restrictions.eq就是QBC运算符
criteria.add(Restrictions.eqProperty(propertyName,otherPropertyName))
1 @SuppressWarnings("unchecked") 2 @Override 3 @Transactional(propagation = Propagation.NOT_SUPPORTED) 4 public List<User> check(String username, String email, String peopleId) { 5 Criteria c = factory.getCurrentSession().createCriteria(User.class); 6 c.add(Restrictions.or(Restrictions.eq("userName", username), 7 Restrictions.or(Restrictions.eq("email", email), Restrictions 8 .eq("peopleId", peopleId)))); 9 List list = c.list(); 10 return list; 11 }
另外简单介绍一下QBC运算符
常用的几个方法:
= Restrictions.eq() 等于
<> Restrictions.not(Exprission.eq()) 不等于
> Restrictions.gt() 大于
>= Restrictions.ge() 大于等于
< Restrictions.lt() 小于
<= Restrictions.le() 小于等于
is null Restrictions.isnull() 等于空值
is not null Restrictions.isNotNull() 非空值
like Restrictions.like() 字符串模式匹配
and Restrictions.and() 逻辑与
and Restrictions.conjunction() 逻辑与
or Restrictions.or() 逻辑或
or Restrictions.disjunction() 逻辑或
not Restrictions.not() 逻辑非
in(列表) Restrictions.in() 等于列表中的某一个值
ont in(列表) Restrictions.not(Restrictions.in())不等于列表中任意一个值
between x and y Restrictions.between() 闭区间xy中的任意值
not between x and y Restrictions.not(Restrictions..between()) 小于值X或者大于值y
分页:setFirstResult(num),从第num条记录开始,setMaxResults(num),总共num条记录。 查询:list();
另外还有排序
1 List cats = sess.createCriteria(Cat.class) 2 .add( Restrictions.like("name", "F%") 3 .addOrder( Order.asc("name") ) 4 .addOrder( Order.desc("age") ) 5 .setMaxResults(50) 6 .list(); 7 List cats = sess.createCriteria(Cat.class) 8 .add( Property.forName("name").like("F%") ) 9 .addOrder( Property.forName("name").asc() ) 10 .addOrder( Property.forName("age").desc() ) 11 .setMaxResults(50) 12 .list();
最后,还是建议用Hibernate官方推荐的HQL查询方式。