实体类 :
1 package cn.happy.entity; 2 public class Emp { 3 private Integer empNo; 4 private String empName; 5 public Integer getEmpNo() { 6 return empNo; 7 } 8 public void setEmpNo(Integer empNo) { 9 this.empNo = empNo;10 }11 public String getEmpName() {12 return empName;13 }14 public void setEmpName(String empName) {15 this.empName = empName;16 }17 }
工具类:
1 package cn.happy.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 7 public class HibernateUtil { 8 private static final ThreadLocal sessionTL=new ThreadLocal(); 9 private static Configuration cf;10 private static final SessionFactory factory;11 static{12 try {13 cf=new Configuration().configure();14 factory=cf.buildSessionFactory();15 } catch (Exception e) {16 throw new ExceptionInInitializerError(e);17 }18 }19 public static Session getSession()20 { 21 //sessionTL的get()方法根据当前线程返回其对应的线程内部变量,22 //也就是我们需要的Session,多线程情况下共享数据库连接是不安全的。23 //ThreadLocal保证了每个线程都有自己的Session。24 Session session = (Session)sessionTL.get();25 //如果session为null,则打开一个新的session26 if (session==null) {27 //创建一个数据库连接对象session28 session=factory.openSession();29 //保存该数据库连接session到ThreadLocal中。30 sessionTL.set(session);31 32 }33 //如果当前线程已经访问过数据库了,34 //则从sessionTL中get()就可以获取该线程上次获取过的数据库连接对象。35 return session; 36 }37 /**38 * 关闭Session39 */40 public static void closeSession()41 {42 Session session =(Session)sessionTL.get();43 sessionTL.set(null);44 session.close();45 }46 47 }
测试类:
1 package cn.happy.test; 2 3 import org.hibernate.Session; 4 import org.hibernate.Transaction; 5 import org.junit.Test; 6 7 import cn.happy.entity.Emp; 8 import cn.happy.util.HibernateUtil; 9 10 public class STest {11 Transaction tx;12 Session session;13 Transaction tx2;14 Session session2;15 @Test16 public void testBulk(){17 session = HibernateUtil.getSession();18 tx=session.beginTransaction();19 Emp emp = (Emp)session.get(Emp.class, 1);20 System.out.println(emp);21 tx.commit();22 HibernateUtil.closeSession();23 System.out.println("===================");24 session2 = HibernateUtil.getSession();25 tx2=session2.beginTransaction();26 Emp emp2 = (Emp)session2.get(Emp.class, 1);27 System.out.println(emp2);28 tx2.commit();29 HibernateUtil.closeSession();30 }31 }
小配置:
1 2 56 7 148 9 1210 1113
大配置:
1 2 56 7 29oracle.jdbc.OracleDriver 8jdbc:oracle:thin:@localhost:1521:orcl 9zc 10zc 11 12true 13 14true 15 16org.hibernate.cache.EhCacheProvider 17 18 19true 20 21update 22 23org.hibernate.dialect.Oracle10gDialect 24 25 2627 28
Jar包导入:
package cn.happy.entity;
public class Emp {private Integer empNo;
private String empName;
public Integer getEmpNo() {return empNo;}
public void setEmpNo(Integer empNo) {this.empNo = empNo;}
public String getEmpName() {return empName;}
public void setEmpName(String empName) {this.empName = empName;}
}