首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

hiernate联接类

2012-10-26 
hiernate连接类package com.huawei.ssh.entityimport org.hibernate.Sessionimport org.hibernate.Sessi

hiernate连接类

package com.huawei.ssh.entity;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
?private static Configuration configuration;

?private static SessionFactory sessionFactory;

?private static boolean useThreadLocal = true;

?private static ThreadLocal threadSession = new ThreadLocal();

?private static ThreadLocal threadTransaction = new ThreadLocal();

?/**
? * 获取配置文件
? */
?static {

??try {
???// 创建Configuration对象
???configuration = new Configuration();
???// 读取hibernate.cfg.xml文件
???configuration.configure();
???
???sessionFactory = configuration.buildSessionFactory();
??} catch (Exception e) {
???
???System.out.println("init exception " + e);
??}
?}

?/**
? * @return SessionFactory
? */
?public static SessionFactory getSessionFactory() {
??return sessionFactory;
?}

?/**
? * @return 获取当前session
? */
?public static Session getCurrentSession() {
??
??if (useThreadLocal) {
???Session s = (Session) threadSession.get();
???if (s == null) {
????s = getSessionFactory().openSession();
????threadSession.set(s);
???}
???return s;
??} else {

???return getSessionFactory().getCurrentSession();
??}

?}
?
??? /**
? *关闭session对象
? */
?public static void closeSession()
?{
??Session session = (Session)threadSession.get();
??threadSession.set(null);
??if(session!=null&&session.isOpen())
??{
???session.close();
??}
?}
?
?/**
? * 开始事务
? */
?public static void beginTransaction()
?{
??Transaction tx = (Transaction)threadTransaction.get();
??if(tx==null)
??{
???tx = getCurrentSession().beginTransaction();
???threadTransaction.set(tx);
??}
?}
?
?/**
? * 提交事务
? */
?public static void commitTransaction()
?{
??Transaction tx = (Transaction)threadTransaction.get();
??try
??{
??if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack())
??{
???tx.commit();
???
??}
??threadTransaction.set(null);
??}catch(Exception ex)
??{
???rollbackTransaction();
???System.out.println("回滚 "+ex);
??}
??
?}
?
?/**
? * 回滚事务
? */
?public static void rollbackTransaction()
?{
??
??Transaction tx = (Transaction)threadTransaction.get();
??try
??{
??threadTransaction.set(null);
??if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack())
??{
???tx.rollback();
??}
??}catch(Exception ex)
??{
???System.out.println("Rollback exception "+ex);
??}finally
??{
???closeSession();
??}
?}
}

?

热点排行