Hibernate单例实现(Struts1+Hibernate整合)
大家都知道的一件事情,Hibernate启动时需要加载配置文件,连接数据库并映射对象,这一过程需要大量时间,每次运行测试文件时控制台的反馈已经可以看出来了,那么在整合开发时,必然不能每次数据操作都让Hibernate执行一次这个过程,需要在程序初始化时一并完成,完成这件事情需要单例模式的实现,这一过程是简单的。我们可以如下进行:
package demo;import java.io.Serializable;import org.hibernate.*;import org.hibernate.cfg.Configuration;public final class HibernateUtil {private static SessionFactory sessionFactory;// 单例模式,只创建一次对象private HibernateUtil() {}// 初始化,开销很大,只做一次static {Configuration cfg = new Configuration();cfg.configure();// 不是hibernate.cfg.xml时将文件名传入sessionFactory = cfg.buildSessionFactory();}/** * 相当于JDBC的注册驱动 */public static SessionFactory getSessionFactory() {return sessionFactory;}/** * 相当于JDBC的getConnection<BR> * 注意:和HttpSession无关 */public static Session getSession() {return sessionFactory.openSession();}/** * 保存对象 */public static void add(Object entity) {Session s = null;Transaction tx = null;try {s = HibernateUtil.getSession();tx = s.beginTransaction();s.save(entity);tx.commit();} finally {if (s != null) {s.close();}}}/** * 更新对象 */public static void update(Object entity) {Session s = null;Transaction tx = null;try {s = HibernateUtil.getSession();tx = s.beginTransaction();s.update(entity);tx.commit();} finally {if (s != null) {s.close();}}}/** * 删除对象 */public static void delete(Object entity) {Session s = null;Transaction tx = null;try {s = HibernateUtil.getSession();tx = s.beginTransaction();s.delete(entity);tx.commit();} finally {if (s != null) {s.close();}}}/** * 获得对象 */public static Object get(Class clazz, Serializable id) {Session s = null;try {s = HibernateUtil.getSession();Object obj = s.get(clazz, id);return obj;} finally {if (s != null) {s.close();}}}}
package test.plugin;import javax.servlet.ServletException;import org.apache.struts.action.ActionServlet;import org.apache.struts.action.PlugIn;import org.apache.struts.config.ModuleConfig;public class HibernatePlugIn implements PlugIn {@Overridepublic void destroy() {System.out.println("destroy method in hibernate plugin");SessionFactoryManager.closeSessionFactory();}@Overridepublic void init(ActionServlet actionServlet, ModuleConfig config)throws ServletException {System.out.println("init method in hibernate plugin");SessionFactoryManager.openSessionFactory();}}
package test.plugin;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class SessionFactoryManager {private static Configuration configuration = null;private static SessionFactory sessionFactory = null;private SessionFactoryManager() {}static {configuration = new Configuration();configuration.configure();sessionFactory = configuration.buildSessionFactory();}public static SessionFactory openSessionFactory() {return sessionFactory;}public static Session getSession() {return sessionFactory.openSession();}public static void closeSessionFactory() {if (sessionFactory != null && sessionFactory.isClosed() == false) {sessionFactory.close();}}}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"><struts-config>… … …<plug-in className="test.plugin.HibernatePlugIn"></plug-in></struts-config>
package test.action;import java.io.PrintWriter;import java.util.List;import javax.servlet.http.*;import org.apache.struts.action.*;import org.hibernate.*;import org.hibernate.criterion.Restrictions;import test.bean.User;import test.plugin.SessionFactoryManager;public class HibernateTestAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {PrintWriter out = response.getWriter();Session s = SessionFactoryManager.getSession();try {// 使用Criteria进行条件查询,参数是实体BeanCriteria c = s.createCriteria(User.class);//条件是name=?c.add(Restrictions.eq("name", "Sarin"));List<User> list = c.list();for (User user : list) {out.println(user.getId() + "<br>");}} finally {if (s != null) {s.close();}}return null;}}