Hibernate的批量查询——原生sql查询
Posted Dream
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate的批量查询——原生sql查询相关的知识,希望对你有一定的参考价值。
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查询的主要内容,如果未能解决你的问题,请参考以下文章