先来一个简单的示例
1 /** 2 * 根据姓名查询用户 3 * @param name 姓名 4 * @return 用户对象 5 */ 6 public User getUserBynName(String name){ 7 User user = null; 8 Session session = null; 9 try { 10 session = HibernateUtils.getSession(); 11 String hql = " FROM User as user WHERE user.name = :name "; 12 Query query = session.createQuery(hql); 13 query.setString("name",name); 14 user = (User) query.uniqueResult(); 15 }finally { 16 if (session != null){ 17 session.close(); 18 } 19 } 20 return user; 21 }
11 String hql = " FROM User as user WHERE user.name = ?";
12 Query query = session.createQuery(hql);
13 query.setString(1,name);
这样也行,但不推荐。注意,索引从1开始
1 public List<User> getUsersByName(String name){ 2 List<User> users = null; 3 Session session = null; 4 try { 5 session = HibernateUtils.getSession(); 6 /*这里查的是User对象,不是user表,支持多态*/ 7 String hql = " FROM User as user WHERE user.name LIKE :name "; 8 Query query = session.createQuery(hql); 9 query.setString("name",name+"%"); 10 users = query.list(); 11 }finally { 12 if (session != null){ 13 session.close(); 14 } 15 } 16 return users; 17 }
分页查询
1 public List<User> getUsersByName(String name){ 2 List<User> users = null; 3 Session session = null; 4 try { 5 session = HibernateUtils.getSession(); 6 /*这里查的是User对象,不是user表,支持多态*/ 7 String hql = " FROM User as user WHERE user.name LIKE :name "; 8 Query query = session.createQuery(hql); 9 query.setString("name",name+"%"); 10 query.setFirstResult(10); 11 query.setMaxResults(5); 12 users = query.list(); 13 }finally { 14 if (session != null){ 15 session.close(); 16 } 17 } 18 return users; 19 }