一、绑定本地session
原理:之前connection实现事务一个道理,2种方法:1、变量下传。2、因为servlet是单线程,和本地当前线程绑定。
配置:
1)配置核心配置文件hibernate.cfg
1 <!--绑定本地session--> 2 <property name="hibernate.current_session_context_class">thread</property>
2)hibernate本身底层已经帮忙绑定当前线程(threadLocal)通过getCurrentSession 获取session。
工具类:
1 package jd.com.test; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 7 public class hibernateUtils { 8 private final static Configuration CONFIURATION; 9 private final static SessionFactory SESSIONFACTORY; 10 static { 11 CONFIURATION=new Configuration().configure(); 12 SESSIONFACTORY=CONFIURATION.buildSessionFactory(); 13 } 14 public static Session getSession(){ 15 return SESSIONFACTORY.openSession(); 16 } 17 public static Session getCurrenSession(){ 18 return SESSIONFACTORY.getCurrentSession(); 19 } 20 }
3)业务层进行事务定义:
1 package jd.com.service.Custorm; 2 3 4 import jd.com.dao.Dao; 5 import jd.com.hibernatepro.Customer; 6 import org.hibernate.Session; 7 import jd.com.dao.hibernateUtils; 8 import org.hibernate.Transaction; 9 import org.junit.Test; 10 11 public class service { 12 @Test 13 public void savobj(){ 14 Customer customer =new Customer(); 15 customer.setName("iio"); 16 Customer customer1 =new Customer(); 17 customer1.setName("ooc"); 18 Session session=hibernateUtils.getCurrenSession(); 19 Transaction tr=session.beginTransaction(); 20 try { 21 Dao dao=new Dao(); 22 dao.saveCustorm(customer); 23 Integer a=2/0; 24 dao.saveCustorm(customer1); 25 tr.commit(); 26 }catch (Exception ex){ 27 ex.printStackTrace(); 28 tr.rollback(); 29 } 30 // 不要关闭session 线程结束就自动关闭session。 31 32 33 } 34 }
dao层执行:
1 package jd.com.dao; 2 3 import jd.com.hibernatepro.Customer; 4 import org.hibernate.Session; 5 6 public class Dao { 7 public void saveCustorm(Customer custome){ 8 Session session=hibernateUtils.getCurrenSession(); 9 session.save(custome); 10 } 11 }
需要注意的是session不需要释放。当前线程结束就释放session。
简单的条件查询:
1 **Query查询接口** 2 3 1. 具体的查询代码如下 4 // 1.查询所有记录 5 /*Query query = session.createQuery("from Customer"); 6 List<Customer> list = query.list(); 7 System.out.println(list);*/ 8 9 // 2.条件查询: 10 /*Query query = session.createQuery("from Customer where name = ?"); 11 query.setString(0, "tom"); 12 List<Customer> list = query.list(); 13 System.out.println(list);*/ 14 15 // 3.条件查询: 16 /*Query query = session.createQuery("from Customer where name = :aaa and age = :bbb"); 17 query.setString("aaa", "tom"); 18 query.setInteger("bbb", 38); 19 List<Customer> list = query.list(); 20 System.out.println(list);*/ 21 22 ----------