码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2019-11-10 13:17:55      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:占位符   tor   sts   objects   obj   分页查询   span   generator   create   

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();
        }

技术图片

 

 (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();
        }

技术图片

 

 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();
        }

 

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

标签:占位符   tor   sts   objects   obj   分页查询   span   generator   create   

原文地址:https://www.cnblogs.com/zhai1997/p/11829462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!