Hibernate DetachedCriteria
hibernate DetachedCriteria(hibernate 分离/离线查询)
使用DetachedCriteria类可以在session之外构造一个查询条件,而不受session的约束。同时也很好的实现了
分层。并且对于动态查询也有不错的作用。
public static void detachedQuery(String name, Date birthday) {
DetachedCriteriadc=DetachedCriteria.forClass(Users.class);
List<Users> users = null;if (name != null && !"".equals(name)) {
dc.add(Restrictions.eq("username",name));
}
if(birthday!=null&&!"".equals(birthday)){
dc.add(Restrictions.gt("birthday",birthday));
}
users=detachedCriteriaQuery(dc);
if(users!=null&&!users.isEmpty()){
for(Usersuser:users){
System.out.println(user.getUsername()+"-----"
+user.getBirthday());
}
}
}public static List<Users> detachedCriteriaQuery(DetachedCriteria dc) {
List<Users>users=null;
Sessionsession=null;
try{
session=HibernateSessionFactory.getSession();
Criteriacriteria=dc.getExecutableCriteria(session);
users=criteria.list();
}catch(Exceptione){
e.printStackTrace();
}finally{
if(session!=null){
session.close();
}
}
returnusers;
}