Hibernate SessionFactory

the*_*ava 4 java spring hibernate

private HibernateTemplate hibernateTemplate;

        public void setSessionFactory(SessionFactory sessionFactory) {
            this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }
Run Code Online (Sandbox Code Playgroud)

什么是SessionFactory类?我们为什么用它?什么是hibernateTemplate类用于?

<bean id="myUserDAO" class="com.mysticcoders.mysticpaste.services.ContactSerImpl">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.mysticcoders.mysticpaste.model.Contact</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>
Run Code Online (Sandbox Code Playgroud)

这在bean中做了什么

Jig*_*shi 8

应用程序从Session Factory获取会话实例. SessionFactory主要是Singleton在应用程序中配置,如果您使用的是Spring,它将在应用程序上下文中配置为单例.

SessionFactory 缓存生成Hibernate在运行时使用的SQL语句和其他映射元数据.

已在一个工作单元中读取的缓存数据,可在未来的工作单元中重复使用.

您可以从Configuration类获取会话工厂的对象

SessionFactory sessionFactory =
Configuration.buildSessionFactory();  
Run Code Online (Sandbox Code Playgroud)

在你的conf.您已使用AnnotationSessionFactoryBean类配置了sessionFactory

bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
Run Code Online (Sandbox Code Playgroud)

并且您已经设置了所需的会话工厂的一些属性.

HibernateTemplate 是Spring提供的一个类:

Helper类简化了Hibernate数据访问代码.在org.springframework.dao异常层次结构之后自动将HibernateExceptions转换为DataAccessExceptions.


Jeg*_*ala 6

  1. SessionFactory作为Interface为整个应用程序或整个hibernate应用程序提供会话对象.

  2. 通常会有一个SessionFactory,可以由所有应用程序线程共享.SessionFactory是线程安全的.

  3. SessionFactory是数据的二级缓存,可在进程或集群级别的事务之间重用.

                                                                          Continue.......
    
    Run Code Online (Sandbox Code Playgroud)