connectionusermanager.java
来自「社区文章采用的是平板、树形自由选择的两种展示方式」· Java 代码 · 共 114 行
JAVA
114 行
/*
* Created on 2007-9-8
* Last modified on 2007-12-20
* Powered by YeQiangWei.com
*/
package com.yeqiangwei.club.dao.hibernate;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.yeqiangwei.club.exception.DAOException;
public class ConnectionUserManager {
private static final Logger logger = Logger.getLogger(ConnectionUserManager.class);
private static SessionFactory sessionFactory = null;
public static final ThreadLocal<Session> localSession = new ThreadLocal<Session>() ;
private static final ThreadLocal<Transaction> transactionThread = new ThreadLocal<Transaction>();
public static void init() throws DAOException {
if(sessionFactory==null){
try{
sessionFactory =
new Configuration().configure("/yeqiangwei.user.hb.xml").buildSessionFactory();
logger.info("SessionFactory Instanced");
}catch(HibernateException e){
logger.error(e.toString());
throw new DAOException(e.getMessage());
}
}
}
public static SessionFactory getSessionFactory() throws DAOException{
if(sessionFactory==null){
ConnectionManager.init();
}
return sessionFactory;
}
public static Session getSession() throws DAOException {
Session session = localSession.get();
if(session==null||!session.isOpen()){
session = sessionFactory.openSession();
localSession.set(session);
}
return session;
}
public static void closeSession() throws DAOException {
Session session = localSession.get();
if (session!= null&&session.isOpen()){
try{
session.close();
localSession.set(null);
}catch(HibernateException e){
logger.error(e.toString());
throw new DAOException(e.getMessage());
}
}
}
public static Transaction beginTransaction() throws DAOException {
try{
Transaction tx = transactionThread.get();
if (tx == null) {
tx = getSession().beginTransaction();
transactionThread.set(tx);
}
return tx;
}catch(HibernateException e){
logger.error(e.toString());
throw new DAOException(e.getMessage());
}
}
/**
* 提交当前Session的Transaction
* @throws HibernateException
*/
public static void commitTransaction() throws DAOException {
try{
Transaction tx = transactionThread.get();
transactionThread.set(null);
if (tx != null) tx.commit();
}catch(HibernateException e){
logger.error(e.toString());
throw new DAOException(e.getMessage());
}
}
/**
* 回滚当前事务
* @throws HibernateException
*/
public static void rollbackTransaction() throws DAOException {
try{
Transaction tx = transactionThread.get();
transactionThread.set(null);
if (tx != null) tx.rollback();
}catch(HibernateException e){
logger.error(e.toString());
throw new DAOException(e.getMessage());
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?