hibernate DetachedCriteria(hibernate 分离/离线查询)
使用DetachedCriteria类可以在session之外构造一个查询条件,而不受session的约束。同时也很好的实现了
分层。并且对于动态查询也有不错的作用。
public static void detachedQuery(String name, Date birthday) {
DetachedCriteria dc = 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 (Users user : users) {
System.out.println(user.getUsername() + "-----"
+ user.getBirthday());
}
}
}
public static List<Users> detachedCriteriaQuery(DetachedCriteria dc) {
List<Users> users = null;
Session session = null;
try {
session=HibernateSessionFactory.getSession();
Criteria criteria = dc.getExecutableCriteria(session);
users = criteria.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
return users;
}