首页 > 代码库 > Hibernate 查询方法

Hibernate 查询方法

 1 1、简单查询: 2  public User select(User user) { 3         User newUser; 4         try { 5             newUser = (User) session.get(User.class,user.getEmails()); 6             return newUser; 7         } catch (Exception e) { 8             log.error("查询失败", e); 9             return null;10         } finally {11             HibernateUtil.closeSession();12         }13     }14 2、 用?15  public List<User>select(User user){  16   String hql = "from user where emails= ? and password= ?";  17   Query query = session.createQuery(hql);  18   query.setString(0, user.getEmails());  19   query.setString(1, user.getPassword());  20   List<User> list = query.list();  21   session.close();  22   return list;  23  }  24   25 3、用":+命名":  26  public List<User> select(User user){  27   Session session = HibernateSessionFactory.getSession();  28   String hql = "from user where emails= :e and password= :p";  29   Query query = session.createQuery(hql);  30 {31   query.setString("e", user.getEmails());  32   query.setString("p", user.getPassword());  33 }else{34  query.setParameter("e", user.getEmails());  35   query.setParameter("p", user.getPassword());  36 }else{37  query.setProperties(user);  38 }39   List<User> list = query.list();  40   session.close();  41   return list;  42  }  43 4、使用条件查询(Criteria) 没有hql语句 :44  public List<User> select(User user){  45   Criteria cri = session.createCriteria(User.class);  46   cri.add(Restrictions.eq("emails", user.getEmails()));  47   cri.add(Restrictions.eq("password", user.getPassword()));  48   List<User> list = cri.list();  49   session.close();  50   return list;  51  }  52    53    54 5、离线条件查询:55  public List<User> select(User user){  56   DetachedCriteria dc = DetachedCriteria.forClass(User.class);  57   dc .add(Restrictions.eq("emails", user.getEmails()));  58   dc .add(Restrictions.eq("password", user.getPassword()));  59   Criteria cri = dc.getExecutableCriteria(session);  60   List<User> list = cri.list();  61   session.close();  62   return list;  63  }   64 6、分页查询:65 1)  setFirstResult(int):指定从指定的位置开始查询66 2)  setMaxResult(int):指定一次查询的对象数量。  

 

Hibernate 查询方法