创建HibernateUtils类,便于直接获取session
package com.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration().configure();
//根据配置信息,创建SessionFactory对象
sessionFactory = configuration.buildSessionFactory();
}
//获得session=>获得全新session
public static Session openSession(){
//获得session
Session session = sessionFactory.openSession();
return session;
}
//获得session=>获得与线程绑定的session
public static Session getCurrentSession(){
Session session = sessionFactory.getCurrentSession();
return session;
}
}
基本查询
@Test
public void test_01(){
//获得session对象
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
String hql = "from Customer";
Query query = session.createQuery(hql);
List<Customer> list = query.list();
System.out.println(list);
transaction.commit();
//transaction.rollback();
session.close();
}
条件查询之使用'?'占位符
@Test
public void test_02(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//-----------------------------------------
String hql = "from Customer where cust_id = ?0";
Query query = session.createQuery(hql);
query.setParameter(0,3l);
Customer cs = (Customer) query.uniqueResult();
/**
* 此处hql语句中的占位符若写成以下格式则会报错,貌似是因为Hibernate版本较高不支持
* String hql = "from Customer where cust_id = 0";
* Query query = session.createQuery(hql);
* query.setParameter(0,3l);
* Customer cs = (Customer) query.uniqueResult();
*/
//-------------------------------------------
System.out.println(cs);
transaction.commit();
session.close();
}
条件查询之使用':name'占位符
@Test
public void test_03(){
//使用占位符 :name
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
String hql = "from Customer where cust_id = :cust_id";
Query query = session.createQuery(hql);
query.setParameter("cust_id",1l);
Customer customer = (Customer) query.uniqueResult();
System.out.println(customer);
transaction.commit();
session.close();
}
分页查询:
@Test public void test_04(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); String hql = "from Customer"; Query query = session.createQuery(hql); query.setFirstResult(0);//设置分页查询起始位置,下标从0开始 query.setMaxResults(3);//设置一次查询多少条记录 List<Customer> list = query.list(); System.out.println(list); }