第一种,适合sql语言水平比较高的人用
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文件中字段名大小写一致。
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 }
分页: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查询方式。
Hibernate与数据库交互方式和Hibernate常用的几个方法
原文:http://www.cnblogs.com/zhaojinhui/p/4023130.html