- HibernateUtil ThreadLocal
- import java.sql.SQLException;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import java.sql.Connection;
- import org.apache.log4j.Logger;
- import java.io.File;
- public class HibernateUtil {
- /**
- * Loger4j的logger
- */
- private static final Logger logger = Logger.getLogger(HibernateUtil.class);
- /**
- * 存储hibernate session的ThreadLocal
- */
- private static final ThreadLocal sessionThread = new ThreadLocal();
- /**
- * 存储事务的ThreadLocal
- */
- private static final ThreadLocal transactionThread = new ThreadLocal();
- /**
- * Hibernate 的 Session工厂
- */
- private static SessionFactory sessionFactory = null;
- /**
- * 初始化SessionFactory
- *
- * @param file
- * Hibernate配置文件
- */
- public static void initSessionFactory(File file) {
- Configuration config = new Configuration();
- config.configure(file);
- sessionFactory = config.buildSessionFactory();
- }
- /**
- * 获取当前线程绑定的session
- *
- * @return Session
- * @throws HibernateException
- */
- public static Session getSession() {
- Session s = (Session) sessionThread.get();
- if (s == null) {
- s = sessionFactory.openSession();
- sessionThread.set(s);
- } else {
- Connection conn = s.connection();
- try {
- if (conn == null || conn.isClosed()) {
- try {
- s.close();
- } catch (HibernateException e) {
- logger.warn("close session error:" + e.getMessage(), e);
- }
- s = sessionFactory.openSession();
- sessionThread.set(s);
- }
- } catch (SQLException e) {
- throw new HibernateException(e);
- }
- }
- return s;
- }
- /**
- * 取得当前session的事务
- *
- * @return Transaction
- */
- public static Transaction transaction() {
- Transaction transaction = (Transaction) transactionThread.get();
- if (transaction == null) {
- transaction = getSession().beginTransaction();
- transactionThread.set(transaction);
- }
- return transaction;
- }
- /**
- * 提交当前session的事务
- */
- public static void commitTransaction() {
- Transaction transaction = (Transaction) transactionThread.get();
- transactionThread.set(null);
- if (transaction != null)
- transaction.commit();
- }
- /**
- * 回滚当前session的事务
- */
- public static void rollbackTransaction() {
- Transaction tx = (Transaction) transactionThread.get();
- transactionThread.set(null);
- if (tx != null)
- tx.rollback();
- }
- /**
- * 关闭当前线程使用的session
- */
- public static void closeSession() {
- Session session = (Session) sessionThread.get();
- if (session != null) {
- session.clear();
- session.close();
- sessionThread.set(null);
- }
- }
- }
- CloseSessionFilter:
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.*;
- public class CloseSessionFilter implements Filter {
- protected FilterConfig config;
- public void init(FilterConfig config) throws ServletException {
- this.config=config;
- }
- public void destroy() {
- config=null;
- }
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain
- chain) throws IOException, ServletException {
- try{
- chain.doFilter((HttpServletRequest)request,(HttpServletResponse)response);
- }
- finally
- {
- try{
- HibernateUtil.commitTransaction();
- }
- catch(Exception e){
- HibernateUtil.rollbackTransaction();
- }
- finally
- {
- HibernateUtil.closeSession();
- }
- }
- }
- }
- Test.java:
- HibernateUtil.initSessionFactory(new File(Test.class.getClassLoader().getResource
- ("hibernate.cfg.xml").getFile()));
- Session se = HibernateUtil.getSession();
- Query query = se.getNamedQuery("CatgQuery");
- List list= query.list();
- Iterator iter= list.iterator();
- while(iter.hasNext()){
- Catg temp=(Catg)iter.next();
- System.out.println(temp.getId() + ":" + temp.getCname()
- +","+temp.getCount());
- }
- HibernateUtil.closeSession();
HibernateUtil ThreadLocal
最新推荐文章于 2021-06-30 18:42:17 发布