Hibernate的批量查询——Criteria

1、查询所有的学生信息:

public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Criteria criteria=session.createCriteria(Student.class);
            List<Student>list= criteria.list();
            System.out.println(list);
            transaction.commit();
            session.close();
        }

Hibernate的批量查询——Criteria

 2、条件查询:

运算符与对应的英文缩写:

> gt  >=ge  <lt  <=le  ==eq

!=ne  in:in  between and::between

like:like  is not null:isNotNull  

or:or  and:and

(1)eq的运用:

public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Criteria criteria=session.createCriteria(Student.class);
            criteria.add(Restrictions.eq("sex","女"));
            List<Student>list= criteria.list();
            System.out.println(list);
            transaction.commit();
            sessio

Hibernate的批量查询——Criteria

 (2)like的运用:

public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Criteria criteria=session.createCriteria(Student.class);
            criteria.add(Restrictions.like("sname","许__"));
            List<Student>list= criteria.list();
            System.out.println(list);
            transaction.commit();
            session.close();
        }

Hibernate的批量查询——Criteria

 3、分页查询:

需要事先设置起始位置和查询的数量。

public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Criteria criteria=session.createCriteria(Student.class);
            criteria.add(Restrictions.eq("sex","女"));
            criteria.setFirstResult(1);
            criteria.setMaxResults(2);
            List<Student>list= criteria.list();
            System.out.println(list);
            transaction.commit();
            session.close();
        }

Hibernate的批量查询——Criteria

4、总记录数的获取:

public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Criteria criteria=session.createCriteria(Student.class);
            criteria.setProjection(Projections.rowCount());//聚合函数获得总行数
            Long rowNum= (Long) criteria.uniqueResult();
            System.out.println(rowNum);
            List<Student>list= criteria.list();
            System.out.println(list);
            transaction.commit();
            session.close();
        }

Hibernate的批量查询——Criteria

相关推荐