Hibernate查询方式:HQL和Criteria

1.HQL查询方法一般使用的比较多,一般是通过query方式来查询的.例子如下:
/**
* 根据名字来查询
*
* @param name
*/
static void query(String name) {
Session s = null;
try{
s = HibernateUtil.getSession();
// String hql = "from User as user where user.name=?";
String hql = "from User as user where user.name=:name";//采用这种方式的时候,就用setString(String,String)
Query query = s.createQuery(hql);
query.setString("name", name);
List list = query.list();
//查询从某一条开始到某一条的分页
query.setFirstResult(10);
query.setMaxResults(20);
for(int i = 0;i System.out.println(list.get(i));
}
}finally{
if(s!=null){
s.close();
}
}
}

2.而Criteria是一种比HQL更面向对象的查询方式:

创建方式如下:Criteria crit = session.createCriteria(Object.class);

crit.add(Restrictions.eqProperty(a,b));
:
static void query(String name) {
Session s = null;
try{
s = HibernateUtil.getSession();
Criteria c = s.createCriteria(User.class);
c.add(Restrictions.eq("name", name));
c.add(Restrictions.gt("birthday", new Date()));
List list = c.list();
for(int i = 0;i System.out.println(list.get(i));
}
}finally{
if(s!=null){
s.close();
}
}
}

你可能感兴趣的:(Hibernate,C,C++,C#)