之前给大家介绍过一些Hibernate入门的内容,下面要给大家带来的是一个Hibernate使用原生sql的实例,一起来看一下吧!
package com.kd.test; import java.util.Arrays; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.NativeQuery; import org.junit.Test; import com.kd.entity.User; public class NativeSqlDemo { @Test // 原生sql查询列表 public void fun1() { // 获取配置文件对象 Configuration config = new Configuration() .configure(); // 构建SessionFactory SessionFactory factory = config.buildSessionFactory(); // 生产session,可以理解为jdbc中的connection Session session = factory.openSession(); // 开启事务 Transaction transaction = session.beginTransaction(); //创建sql语句 String sql = "select * from user"; //创建sqlquery执行语句 NativeQuery query = session.createSQLQuery(sql); // List<Object[]> list = query.list(); query.addEntity(User.class); List list = query.list(); transaction.commit(); session.close(); // for (Object[] objects : list) { // System.out.println(Arrays.toString(objects)); // } System.out.println(list); } @Test // 原生sql的条件查询 public void fun2() { // 获取配置文件对象 Configuration config = new Configuration() .configure(); // 构建SessionFactory SessionFactory factory = config.buildSessionFactory(); // 生产session,可以理解为jdbc中的connection Session session = factory.openSession(); // 开启事务 Transaction transaction = session.beginTransaction(); String sql = "select * from user where id=?"; NativeQuery query = session.createSQLQuery(sql); query.setParameter(1, 1); query.addEntity(User.class); User user = (User) query.uniqueResult(); transaction.commit(); session.close(); System.out.println(user); } @Test // 原生sql的分页查询 public void fun3() { // 获取配置文件对象 Configuration config = new Configuration() .configure(); // 构建SessionFactory SessionFactory factory = config.buildSessionFactory(); // 生产session,可以理解为jdbc中的connection Session session = factory.openSession(); // 开启事务 Transaction transaction = session.beginTransaction(); String sql = "select * from user limit ?,?"; NativeQuery query = session.createSQLQuery(sql); query.setParameter(1, 0); query.setParameter(2, 3); query.addEntity(User.class); List list = query.list(); transaction.commit(); session.close(); System.out.println(list); } }
以上内容源于网络,仅供参考,希望对你有所帮助。
更多实例,请继续通过奇Q工具网的java实例栏目来进行了解吧!更多的java程序代码例子可以为你分享。
推荐阅读: