Hibernate原生sql查詢簡單入門
阿新 • • 發佈:2019-01-10
package cn.zhicheng.domain; import java.util.List; import org.hibernate.Criteria; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import cn.itheima.utils.HibernateUtils; public class Demo06 { @Test //原生sql查詢 public void test(){ Session s = HibernateUtils.openSession(); Transaction tx = s.beginTransaction(); String sql = "select * from cst_customer"; SQLQuery query = s.createSQLQuery(sql); SQLQuery addEntity = query.addEntity(Customer.class); List<Customer> list = addEntity.list(); System.out.println(list); tx.commit(); s.close(); } @Test //原生sql條件查詢佔位符 public void test2(){ Session s = HibernateUtils.openSession(); Transaction tx = s.beginTransaction(); String sql = "select * from cst_customer where cust_id = ?"; SQLQuery query = s.createSQLQuery(sql); query.setParameter(0, 1l); SQLQuery addEntity = query.addEntity(Customer.class); List<Customer> list = addEntity.list(); System.out.println(list); tx.commit(); s.close(); } @Test //原生sql分頁查詢 public void test3(){ Session s = HibernateUtils.openSession(); Transaction tx = s.beginTransaction(); String sql = "select * from cst_customer limit ?,? "; SQLQuery query = s.createSQLQuery(sql); query.setParameter(0, 0); query.setParameter(1, 1); SQLQuery addEntity = query.addEntity(Customer.class); List<Customer> list = addEntity.list(); System.out.println(list); tx.commit(); s.close(); } }