条件查询
、 第一种,用?占位符,如: //登录(用?占位符) public List<UserPO> LoginUser(UserPO up)throws Exception{ Session session = HibernateSessionFactory.getSession(); String hql = "from UserPO where name = ? and pwd= ?"; Query query = session.createQuery(hql); query.setString(, up.getName()); query.setString(, up.getPwd()); List<UserPO> list = query.list(); session.close(); return list; } 、用“:+命名”占位符,如: //登录(用":命名"占位符) public List<UserPO> LoginUser2(UserPO up)throws Exception{ Session session = HibernateSessionFactory.getSession(); String hql = "from UserPO where name = :n and pwd= :p"; Query query = session.createQuery(hql); query.setString("n", up.getName()); query.setString("p", up.getPwd()); List<UserPO> list = query.list(); session.close(); return list; } 2.1、使用这种占位符还可以这样设值,如: //登录(用":命名"占位符,用setParameter设值) public List<UserPO> LoginUser3(UserPO up)throws Exception{ Session session = HibernateSessionFactory.getSession(); String hql = "from UserPO where name = :n and pwd= :p"; Query query = session.createQuery(hql); query.setParameter("n", up.getName()); query.setParameter("p",up.getPwd()); List<UserPO> list = query.list(); session.close(); return list; } 使用这种方式不需要写明映射的类型,Hibernate会通过配置自动给我们转,但是由于Hibernate有两种日期格式:Date和TIMESTAMP,所以对于日期类型必须写明映射的类型。写法: 、按照对象进行参数绑定,如: //登录(用":命名"占位符,用setProperties设值,命名参数必须要与被绑定的属性名相同) public List<UserPO> LoginUser4(UserPO up)throws Exception{ Session session = HibernateSessionFactory.getSession(); String hql = "from UserPO where name = :name and pwd= :pwd"; Query query = session.createQuery(hql); query.setProperties(up); List<UserPO> list = query.list(); session.close(); return list; } 、使用条件查询(Criteria),如: //登录(用条件查询 Criteria)完全脱离sql语句和hql语句 public List<UserPO> LoginUser5(UserPO up)throws Exception{ Session session = HibernateSessionFactory.getSession(); Criteria cri = session.createCriteria(UserPO.class); cri.add(Restrictions.eq("name", up.getName())); cri.add(Restrictions.eq("pwd", up.getPwd())); List<UserPO> list = cri.list(); session.close(); return list; } 、离线条件查询,如: //登录(用离线条件查询 DetachedCriteria) public List<UserPO> LoginUser6(UserPO up)throws Exception{ Session session = HibernateSessionFactory.getSession(); DetachedCriteria dc = DetachedCriteria.forClass(UserPO.class); dc.add(Restrictions.eq("name", up.getName())); dc.add(Restrictions.eq("pwd", up.getPwd())); Criteria cri = dc.getExecutableCriteria(session); List<UserPO> list = cri.list(); session.close(); return list; } 使用离线可以将其写在业务层,以参数的形式传入,以减少DAO的代码。 、分页查询:分页查询是数据库应用中的处理方式,query和criteria接口都提供了用于分页查询的方法: ) setFirstResult(int):指定从哪一个对象开始查询,参数是索引位置,从0开始。 ) setMaxResult(int):指定一次最多查询的对象数量。
查询所有记录:
/** * 查询所有的记录 */ public static List selectAll() { List list = null; try { session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction(); Query q = session.createQuery("from User1"); list = q.list(); tran.commit(); } catch (Exception e) { e.printStackTrace(); } finally { HibernateSessionFactory.closeSession(); } return list; }