MySessionFactory

  1 package com.ORM;
  2 
  3 import org.hibernate.HibernateException;
  4 import org.hibernate.Session;
  5 import org.hibernate.cfg.Configuration;
  6 
  7 /**
  8  * Configures and provides access to Hibernate sessions, tied to the
  9  * current thread of execution.  Follows the Thread Local Session
 10  * pattern, see {@link http://hibernate.org/42.html }.
 11  */
 12 public class MySessionFactory {
 13 
 14     /** 
 15      * Location of hibernate.cfg.xml file.
 16      * Location should be on the classpath as Hibernate uses  
 17      * #resourceAsStream style lookup for its configuration file. 
 18      * The default classpath location of the hibernate config file is 
 19      * in the default package. Use #setConfigFile() to update 
 20      * the location of the configuration file for the current session.   
 21      */
 22     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 23     private static final ThreadLocal threadLocal = new ThreadLocal();
 24     private  static Configuration configuration = new Configuration();
 25     private static org.hibernate.SessionFactory sessionFactory;
 26     private static String configFile = CONFIG_FILE_LOCATION;
 27 
 28     static {
 29         try {
 30             configuration.configure(configFile);
 31             sessionFactory = configuration.buildSessionFactory();
 32         } catch (Exception e) {
 33             System.err
 34                     .println("%%%% Error Creating SessionFactory %%%%");
 35             e.printStackTrace();
 36         }
 37     }
 38     private MySessionFactory() {
 39     }
 40     
 41     /**
 42      * Returns the ThreadLocal Session instance.  Lazy initialize
 43      * the <code>SessionFactory</code> if needed.
 44      *
 45      *  @return Session
 46      *  @throws HibernateException
 47      */
 48     public static Session getSession() throws HibernateException {
 49         Session session = (Session) threadLocal.get();
 50 
 51         if (session == null || !session.isOpen()) {
 52             if (sessionFactory == null) {
 53                 rebuildSessionFactory();
 54             }
 55             session = (sessionFactory != null) ? sessionFactory.openSession()
 56                     : null;
 57             threadLocal.set(session);
 58         }
 59 
 60         return session;
 61     }
 62 
 63     /**
 64      *  Rebuild hibernate session factory
 65      *
 66      */
 67     public static void rebuildSessionFactory() {
 68         try {
 69             configuration.configure(configFile);
 70             sessionFactory = configuration.buildSessionFactory();
 71         } catch (Exception e) {
 72             System.err
 73                     .println("%%%% Error Creating SessionFactory %%%%");
 74             e.printStackTrace();
 75         }
 76     }
 77 
 78     /**
 79      *  Close the single hibernate session instance.
 80      *
 81      *  @throws HibernateException
 82      */
 83     public static void closeSession() throws HibernateException {
 84         Session session = (Session) threadLocal.get();
 85         threadLocal.set(null);
 86 
 87         if (session != null) {
 88             session.close();
 89         }
 90     }
 91 
 92     /**
 93      *  return session factory
 94      *
 95      */
 96     public static org.hibernate.SessionFactory getSessionFactory() {
 97         return sessionFactory;
 98     }
 99 
100     /**
101      *  return session factory
102      *
103      *    session factory will be rebuilded in the next call
104      */
105     public static void setConfigFile(String configFile) {
106         MySessionFactory.configFile = configFile;
107         sessionFactory = null;
108     }
109 
110     /**
111      *  return hibernate configuration
112      *
113      */
114     public static Configuration getConfiguration() {
115         return configuration;
116     }
117 
118 }
  1 package com.service;
  2 
  3 import java.util.List;
  4 
  5 import com.ORM.*;
  6 import com.base.*;
  7 import org.hibernate.*;
  8 
  9 /** 系统用户管理接口实现 */
 10 public class AdminServiceImpl extends BaseLog implements AdminService {
 11 
 12     /** 系统管理员登录 */
 13     public Admin adminLogin(String loginName, String loginPwd) throws Exception {
 14         Session session = MySessionFactory.getSession();
 15         Transaction tx = null;
 16         Admin admin = null;
 17         try{
 18             String hql = "select a from Admin as a where a.loginName=:loginName and a.loginPwd=:loginPwd";
 19             Query query = session.createQuery(hql);
 20             query.setString("loginName", loginName);
 21             query.setString("loginPwd", loginPwd);
 22             query.setMaxResults(1);
 23             tx = session.beginTransaction();
 24             admin = (Admin)query.uniqueResult();
 25             tx.commit();
 26         }catch(Exception ex){
 27             if(tx!=null)tx.rollback();
 28             logger.info("在执行AdminServiceImpl类中的adminLogin方法时出错:
");
 29             ex.printStackTrace();
 30         }finally{
 31             MySessionFactory.closeSession();
 32         }    
 33         return admin;
 34     }
 35 
 36     /** 新增管理员 */    
 37     public boolean addAdmin(Admin admin) throws Exception {
 38         Session session = MySessionFactory.getSession();
 39         Transaction tx = null;
 40         boolean status = false;
 41         try{
 42             tx = session.beginTransaction();
 43             session.save(admin);
 44             tx.commit();
 45             status = true;
 46         }catch(Exception ex){
 47             if(tx!=null)tx.rollback();
 48             logger.info("在执行AdminServiceImpl类中的addAdmin方法时出错:
");
 49             ex.printStackTrace();
 50         }finally{
 51             MySessionFactory.closeSession();
 52         }    
 53         return status;
 54     }
 55 
 56     /** 浏览管理员 */
 57     public List browseAdmin() throws Exception {
 58         Session session = MySessionFactory.getSession();
 59         Transaction tx = null;
 60         List list = null;
 61         try{
 62             Query query = session.createQuery("from Admin as a order by a.id");
 63             tx = session.beginTransaction();
 64             list = query.list();
 65             tx.commit();
 66             if (!Hibernate.isInitialized(list))Hibernate.initialize(list);
 67         }catch(Exception ex){
 68             if(tx!=null)tx.rollback();
 69             logger.info("在执行AdminServiceImpl类中的browseAdmin方法时出错:
");
 70             ex.printStackTrace();
 71         }finally{
 72             MySessionFactory.closeSession();
 73         }    
 74         return list;
 75     }
 76 
 77     /** 删除指定的管理员 */
 78     public boolean delAdmin(Integer id) throws Exception {
 79         Session session = MySessionFactory.getSession();
 80         Transaction tx = null;
 81         boolean status = false;
 82         try{
 83             tx = session.beginTransaction();
 84             Admin admin = (Admin)session.load(Admin.class, id);
 85             session.delete(admin);
 86             tx.commit();
 87             status = true;
 88         }catch(Exception ex){
 89             if(tx!=null)tx.rollback();
 90             logger.info("在执行AdminServiceImpl类中的delAdmin方法时出错:
");
 91             ex.printStackTrace();
 92         }finally{
 93             MySessionFactory.closeSession();
 94         }    
 95         return status;
 96     }
 97 
 98     /** 装载指定的管理员 */
 99     public Admin loadAdmin(Integer id) throws Exception {
100         Session session = MySessionFactory.getSession();
101         Transaction tx = null;
102         Admin admin = null;
103         try{
104             tx = session.beginTransaction();
105             admin = (Admin)session.get(Admin.class, id);
106             tx.commit();
107         }catch(Exception ex){
108             if(tx!=null)tx.rollback();
109             logger.info("在执行AdminServiceImpl类中的loadAdmin方法时出错:
");
110             ex.printStackTrace();
111         }finally{
112             MySessionFactory.closeSession();
113         }    
114         return admin;
115     }
116 
117     /** 更新管理员 */    
118     public boolean updateAdmin(Admin admin) throws Exception {
119         Session session = MySessionFactory.getSession();
120         Transaction tx = null;
121         boolean status = false;
122         try{
123             tx = session.beginTransaction();
124             session.update(admin);
125             tx.commit();
126             status = true;
127         }catch(Exception ex){
128             if(tx!=null)tx.rollback();
129             logger.info("在执行AdminServiceImpl类中的updateAdmin方法时出错:
");
130             ex.printStackTrace();
131         }finally{
132             MySessionFactory.closeSession();
133         }    
134         return status;
135     }
136 }
原文地址:https://www.cnblogs.com/sharpest/p/5821711.html