Hibernate的批量查询——原生sql查询

时间:2022-05-13 16:34:41

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

(1)查询结果中,一条信息放入到一个数组中,从list集合中取出数组,并对数组进行遍历。

public class GeneratorTest {
    public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            String sql="Select * from Student";
            SQLQuery sqlQuery=session.createSQLQuery(sql);
            List<Object[]>list= sqlQuery.list();
            for(Object[] objects:list){
                System.out.println(Arrays.toString(objects));
            }
            System.out.println(list);
            transaction.commit();
            session.close();
        }

Hibernate的批量查询——原生sql查询

 

 (2)直接封装到学生对象中,将对象存储到list集合:

public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            String sql="Select * from Student";
            SQLQuery sqlQuery=session.createSQLQuery(sql);
            sqlQuery.addEntity(Student.class);
            List<Student>list= sqlQuery.list();
            System.out.println(list);
            transaction.commit();
            session.close();
        }

Hibernate的批量查询——原生sql查询

 

 2、占位符的使用:

    public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            String sql="Select * from Student where sex=?";
            SQLQuery sqlQuery=session.createSQLQuery(sql);
            sqlQuery.setParameter(0,"");
            sqlQuery.addEntity(Student.class);
            List<Student>list= sqlQuery.list();
            System.out.println(list);
            transaction.commit();
            session.close();
        }

3、分页查询:

public static void testSel() {
            Session session = HibernateUtils.openSession();
            Transaction transaction = session.beginTransaction();
            String sql="Select * from Student limit ?,?";
            SQLQuery sqlQuery=session.createSQLQuery(sql);
            sqlQuery.setParameter(0,0);
            sqlQuery.setParameter(1,1);
            sqlQuery.addEntity(Student.class);
            List<Student>list= sqlQuery.list();
            System.out.println(list);
            transaction.commit();
            session.close();
        }