(五)HibernateSessionFactory分析

        在MyEclipse里面为了简化开发提供有这样的工具类,这个工具类,这个工具类的主要目的是取得SessionFactroy以及Session对象.现在最为重要的实际上是Session对象,所有的数据操作由此展开.

范例:分析HibernateSessionFactory

package cn.zwb.dbc;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSessionFactory {
		//表示提供有ThreadLocal对象保存,适合于进行线程的准切处理
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;//连接工厂
	
    private static Configuration configuration = new Configuration();//读取配置文件
    private static ServiceRegistry serviceRegistry; //服务注册类
    	//静态代码块,可以在类加载的时候执行一次
	static {
    	try {
			configuration.configure();//读取配置文件
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
				//在静态块中就已经准备好了SessionFactory类的对象
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {  //构造方法私有化,本类不需要提供构造
    }
	
	/**
     *取得Session对象,对象是通过ThreadLocal类取得的,如果没有保存的Session,那么会重新连接
     *
     *  @return Session   
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        	//为了防止用户可能重复的使用Session对象,是通过保存在ThreadLocal类中的Session直接使用的
    	Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {//如果第一次使用或者关闭了
			if (sessionFactory == null) {		//判断此时存在有SessionFactory类对象
				rebuildSessionFactory();		//如果SessionFactory不存在,则重新创建一个SessionFactroy
			}
			
			//判断此时是否取得了SessionFactory类对象,如果取得,则使用openSession()打开新Session,否则返回空
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);  //为了防止可能重复使用Session
		}

        return session;
    }

	/**
     *  重新进行SessionFactory类对象的创建
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  所有操作的最后一定要关闭Session,在业务层中关闭
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();//取得已有的Session
        threadLocal.set(null);//清空ThreadLocal的保存

        if (session != null) {//将Session进行关闭
            session.close();
        }
    }

	/**
	 *取得SessionFactory类的对象
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	/**
	 * 	取得Configuration的对象
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

        这个类只要使用就可以取得Session.SessionFactroy,Configuration类的对象,至于如何取得,暂时不用关心,因为Hibernate不可能单独使用,都会结合到Spring上使用,

范例:使用这个连接工厂类

package cn.zwb.test;
import cn.zwb.dbc.HibernateSessionFactory;
import cn.zwb.pojo.Member;

public class TestemberInsertDemo {
	public static void main(String[] args) {
		//设置vo属性内容内容的操作应该由控制层完成
		Member vo=new Member();
		vo.setMid("ww低洼地zwb请求aaa");
		vo.setName("SHITH");
		vo.setAge(10);
		vo.setSalary(1000.0);
		vo.setNode("wwwwwwww");
		vo.setBirthday(151561.0);
		//2.数据的保存操作应该由数据层完成
		HibernateSessionFactory.getSession().save(vo);
		//3.事务的Session的关闭应该由业务层完成
		HibernateSessionFactory.getSession().beginTransaction().commit();
		HibernateSessionFactory.closeSession();
	}
}


阅读更多

有关于HibernateSessionFactory问题

09-04

大家都知道SessionFactory是重量级封装,创建一个SessionFactory是非常耗资源的。所以,一般而言,我们都会写一个静态的方法来获得SessionFactory,以下代码是myEclipse自动生成的代码。rnrnimport org.hibernate.HibernateException;rnimport org.hibernate.Session;rnimport org.hibernate.cfg.Configuration;rnrn/**rn* Configures and provides access to Hibernate sessions, tied to thern* current thread of execution. Follows the Thread Local Sessionrn* pattern, see @link http://hibernate.org/42.html.rn*/rnpublic class HibernateSessionFactory rnrn /** rn * Location of hibernate.cfg.xml file.rn * NOTICE: Location should be on the classpath as Hibernate usesrn * #resourceAsStream style lookup for its configuration file. Thatrn * is place the config file in a Java package - the default locationrn * is the default Java package. rn * Examples: rn * CONFIG_FILE_LOCATION = "/hibernate.conf.xml". rn * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml". rn */rn private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";rnrn /** Holds a single instance of Session */rn private static final ThreadLocal threadLocal = new ThreadLocal();rnrn /** The single instance of hibernate configuration */rn private static final Configuration cfg = new Configuration();rnrn /** The single instance of hibernate SessionFactory */rn private static org.hibernate.SessionFactory sessionFactory;rnrn /**rn * Returns the ThreadLocal Session instance. Lazy initializern * the SessionFactory if needed.rn *rn * @return Sessionrn * @throws HibernateExceptionrn */rn public static Session currentSession() throws HibernateException rn Session session = (Session) threadLocal.get();rnrn if (session == null || !session.isOpen()) rn if (sessionFactory == null) rn try rn cfg.configure(CONFIG_FILE_LOCATION);rn sessionFactory = cfg.buildSessionFactory();rn catch (Exception e) rn System.errrn .println("%%%% Error Creating SessionFactory %%%%");rn e.printStackTrace();rn rn rn session = (sessionFactory != null) ? sessionFactory.openSession()rn : null;rn threadLocal.set(session);rn rnrn return session;rn rnrn /**rn * Close the single hibernate session instance.rn *rn * @throws HibernateExceptionrn */rn public static void closeSession() throws HibernateException rn Session session = (Session) threadLocal.get();rn threadLocal.set(null);rnrn if (session != null) rn session.close();rn rn rnrn /**rn * Default constructor.rn */rn private HibernateSessionFactory() rn rnrnrnrn这样就大大方便了我们的操作。比如:rnSession session = HibernateSessionFactory.currentSession() ; //获取Session对象rnTransaction tx = session.beginTransaction(); //事务开始rn//进行一些操作rnsession.save(obj);rntx.commit(); //关闭事务rn可要注意,之前我们获取了一个session对象,现问:rn是不是每调用一次HibernateSessionFactory.currentSession() ;rn都要对应着HibernateSessionFactory.closeSession();rnrn问题来啦,SessionFactory是非常耗资源的,如果关闭的话,那岂不是性能非常的低下。如果不关闭的话,好像又有点不妥。rn如果我只获取而不关闭的话,会怎样?rnrn初学hibernate,望大虾解答。

HibernateSessionFactory不能初始化

01-30

stdout:[2012-01-30 14:43:56] INFO Environment:479 - Hibernate 3.1.3rnstdout:[2012-01-30 14:43:56] INFO Environment:509 - [color=#FF0000]hibernate.properties not found[/color]rnstdout:[2012-01-30 14:43:56] INFO Environment:525 - using CGLIB reflection optimizerrnstdout:[2012-01-30 14:43:56] INFO Environment:555 - using JDK 1.4 java.sql.Timestamp handlingrnstdout:[2012-01-30 14:43:56] INFO Configuration:1308 - configuring from resource: /hibernate.cfg.xmlrnstdout:[2012-01-30 14:43:56] INFO Configuration:1285 - Configuration resource: /hibernate.cfg.xmlrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabOrderlist.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabOrderlist -> tab_orderlistrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabUser.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabUser -> tab_userrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabAlog.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabAlog -> tab_alogrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabPaylist.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabPaylist -> tab_paylistrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabPaydayrule.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabPaydayrule -> tab_paydayrulernstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabPaymonthrule.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabPaymonthrule -> tab_paymonthrulernstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabAuser.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabAuser -> tab_auserrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabLog.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabLog -> tab_logrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabArole.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabArole -> tab_arolernstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabAoperation.hbm.xmlrnstdout:[2012-01-30 14:43:56] INFO HbmBinder:309 - Mapping class: com.pay.po.TabAoperation -> tab_aoperationrnstdout:[2012-01-30 14:43:56] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabDnauser.hbm.xmlrnstdout:[2012-01-30 14:43:57] INFO HbmBinder:309 - Mapping class: com.pay.po.TabDnauser -> tab_dnauserrnstdout:[2012-01-30 14:43:57] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabPhonearea.hbm.xmlrnstdout:[2012-01-30 14:43:57] INFO HbmBinder:309 - Mapping class: com.pay.po.TabPhonearea -> tab_phonearearnstdout:[2012-01-30 14:43:57] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabCardbin.hbm.xmlrnstdout:[2012-01-30 14:43:57] INFO HbmBinder:309 - Mapping class: com.pay.po.TabCardbin -> tab_cardbinrnstdout:[2012-01-30 14:43:57] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabLimituser.hbm.xmlrnstdout:[2012-01-30 14:43:57] INFO HbmBinder:309 - Mapping class: com.pay.po.TabLimituser -> tab_limituserrnstdout:[2012-01-30 14:43:57] INFO Configuration:469 - Reading mappings from resource: com/pay/po/TabBanklist.hbm.xmlrnstdout:[2012-01-30 14:43:57] INFO HbmBinder:309 - Mapping class: com.pay.po.TabBanklist -> tab_banklistrnstdout:[2012-01-30 14:43:57] INFO Configuration:1419 - [color=#FF0000]Configured SessionFactory: null[/color]rnstdout:[2012-01-30 14:43:57] INFO HbmBinder:2349 - Mapping collection: com.pay.po.TabAuser.tabAoperations -> tab_aoperationrnstdout:[2012-01-30 14:43:57] INFO HbmBinder:2349 - Mapping collection: com.pay.po.TabArole.tabAoperations -> tab_aoperationrnstdout:[2012-01-30 14:43:57] INFO C3P0ConnectionProvider:50 - C3P0 using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/pay?characterEncoding=utf-8rnstdout:[2012-01-30 14:43:57] INFO C3P0ConnectionProvider:51 - Connection properties: user=root, password=****rnstdout:[2012-01-30 14:43:57] INFO C3P0ConnectionProvider:54 - autocommit mode: falsernException in thread "main" java.lang.NoClassDefFoundError:[color=#FF0000] Could not initialize class com.pay.db.HibernateSessionFactory[/color]rn at com.pay.dao.BaseHibernateDAO.closeSession(BaseHibernateDAO.java:19)rn at com.pay.dao.TabOrderlistDAO.findByProperty(TabOrderlistDAO.java:275)rn at com.pay.dao.TabOrderlistDAO.findByCallphone(TabOrderlistDAO.java:313)rn at com.pay.service.OrderListService.loadOrderList(OrderListService.java:688)rn at com.pay.service.OrderListService.getLastPayByPhone(OrderListService.java:729)rn at test.main(test.java:46)rnrnrn用的是c3p0连接池 HibernateSessionFactory看着没啥问题 请教了 还需要什么代码说一声在线等 谢谢大xia

struts2+spring+hibernate 连接HibernateSessionFactory报错

04-09

HibernateSessionFactory和hibernate.cfg.xml 是用Myeclipse生成的。rn在这一步 sessionFactory = configuration.buildSessionFactory();时出现异常,控制台没有异常提示,rn异常直接显示在页面上 :rnHTTP Status 500 - rnrn--------------------------------------------------------------------------------rnrntype Exception reportrnrnmessage rnrndescription The server encountered an internal error () that prevented it from fulfilling this request.rnrnexception rnrnjavax.servlet.ServletExceptionrn org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:490)rn org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:458)rnrnrnroot cause rnrnjava.lang.reflect.InvocationTargetExceptionrn sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn java.lang.reflect.Method.invoke(Unknown Source)rn com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:426)rn com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:273)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:235)rn com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:141)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:85)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:248)rn org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:85)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:124)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:170)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:85)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:104)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:83)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:268)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:75)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:230)rn com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:229)rn com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:227)rn com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.interceptrn ..................rnnote The full stack trace of the root cause is available in the Apache Tomcat/5.5.20 logs.rnrnrnhibernate.cfg.xml 内容:rn[color=#0000FF]rnrnrnrnrnrnrn *********rn jdbc:oracle:thin:@**.**.*.***:1521:ora10grn org.hibernate.dialect.Oracle9Dialectrn logDataSoursern updatern **********rn oracle.jdbc.driver.OracleDriverrn truern rn rnrn[/color]rn敬请那位大侠看看这是什么原因?

没有更多推荐了,返回首页