Hibernate-查询
/** * 一、Session查询 * get()在无主键的情况下返回null * load()在无主键的情况下会产生异常 **/
HibernateSessionFactory.getSession().get(Member.class, "id-a"); HibernateSessionFactory.getSession().load(Member.class, "id-b");
二、Query查询
//Member是pojo类的名称 String hql="from Member as a"; // 返回类型:List<Member> String hql="select a.mid from Member as a";//返回类型:List<String> String hql="select a.mid,a.name,a.sex from Member as a";//返回类型:List<Object[]> //将查询后的结果转换为指定的vo类型,是根据查询返回列的名称自动匹配的 query.setResultTransformer(new AliasToBeanResultTransformer(Member.class)); /** * 限定查询 */ String kw="hello"; String hql="from Member as a where a.age=? and a.mid like ?"; Query query = HibernateSessionFactory.getSession().createQuery(hql); //设值 (索引从0开始) query.setParameter(0, 10); query.setParameter(1, "%"+kw+"%"); List list = query.list(); /** * 统计查询 */ String kw="hello"; String hql="select count(*) from Member as a where a.age=? and a.mid like ?"; Query query = HibernateSessionFactory.getSession().createQuery(hql); //设值 (索引从0开始) query.setParameter(0, 10); query.setParameter(1, "%"+kw+"%"); Object obj = query.uniqueResult(); /** * 分页查询 */ int currentPage=1; int lineSize=2; String hql="from Member as a"; Query query = HibernateSessionFactory.getSession().createQuery(hql); query.setFirstResult((currentPage-1)*lineSize); query.setMaxResults(lineSize); List list = query.list(); /** * 分组查询 */ String hql="select a.sex, count(*) from Member as a where a.age=? group by a.sex"; Query query = HibernateSessionFactory.getSession().createQuery(hql); //设值 (索引从0开始) query.setParameter(0, 10); List list = query.list();