• [spring,hibernate] spring和hibernate的整合


    Spring对Hibernate的集成提供了很好的支持,Spring提供了对sessionfactory的初始化,用户不用再关心session的open,close,同时,Spring还提供了灵活的事务声明.

    本文通过实例简单讲述如何在Spring中集成Hibernate.

    1,将hibernate的配置加入到Spring的配置中(对datasource和sessionfactory进行配置):

    1. <bean id="dataSource"  
    2.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    3.         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
    4.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />  
    5.         <property name="username" value="user" />  
    6.         <property name="password" value="pwd" />  
    7.     </bean>  
    8.     <bean id="mySessionFactory"  
    9.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
    10.         <property name="dataSource" ref="dataSource" />  
    11.         <property name="mappingResources">  
    12.             <list>  
    13.                 <value>com/test/spring/hibernate/Hbtest.hbm.xml  
    14.                 </value>  
    15.             </list>  
    16.         </property>  
    17.         <property name="hibernateProperties">  
    18.             <value>  
    19.                 hibernate.dialect=org.hibernate.dialect.Oracle10gDialect  
    20.                 hibernate.show_sql=true  
    21.                 hibernate.format_sql=true  
    22.                 hibernate.current_session_context_class=thread  
    23.             </value>  
    24.         </property>  
    25.     </bean>  
    <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
            <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
            <property name="username" value="user" />
            <property name="password" value="pwd" />
        </bean>
        <bean id="mySessionFactory"
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="mappingResources">
                <list>
                    <value>com/test/spring/hibernate/Hbtest.hbm.xml
                    </value>
                </list>
            </property>
            <property name="hibernateProperties">
                <value>
                    hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
                    hibernate.show_sql=true
                    hibernate.format_sql=true
                    hibernate.current_session_context_class=thread
                </value>
            </property>
        </bean>
    Hibernate的配置也可以单独放在hibernate.cfg.xml文件中,然后通过如下的配置指向config文件,这样在spring配置中就不要配置dataSource和其他Hibernate相关的信息了.
    1. <bean id="mySessionFactory"  
    2.     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
    3.     <property name="configLocation" value="classpath:conf/Hibernate.cfg.xml" />  
    4. </bean>  
        <bean id="mySessionFactory"
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="configLocation" value="classpath:conf/Hibernate.cfg.xml" />
        </bean>
    2,将sessionfactory注入到DAO中,通过sessionfactory操作Hibernate提供的API:
    1. <bean id="PlainHibernateDAO" class="com.test.spring.hibernate.PlainHibernateDAO">  
    2.     <property name="sessionFactory" ref="mySessionFactory" />  
    3. </bean>  
        <bean id="PlainHibernateDAO" class="com.test.spring.hibernate.PlainHibernateDAO">
            <property name="sessionFactory" ref="mySessionFactory" />
        </bean>
    应用实例:

    1,通过继承HibernateDaoSupport 或者自己实例化HibernateTemplate来使用HibernateTemplate,HibernateTemplate 会确保当前Hibernate的 Session 对象的正确打开和关闭,并直接参与到事务管理中去,不要用户去管session的打开和关闭.然后直接调用HibernateTemplate提供的方法.

    1. public class DAOSupportDAO extends HibernateDaoSupport {  
    2.   
    3.     public void persist2(Hbtest transientInstance) {  
    4.         log.debug("persisting Hbtest instance");  
    5.         try {  
    6.             this.getHibernateTemplate().save(transientInstance);  
    7.             log.debug("persist successful");  
    8.         } catch (RuntimeException re) {  
    9.             log.error("persist failed", re);  
    10.             throw re;  
    11.         }  
    12.     }  
    13.   
    14. ...  
    15.   
    16. }  
    public class DAOSupportDAO extends HibernateDaoSupport {
    
        public void persist2(Hbtest transientInstance) {
            log.debug("persisting Hbtest instance");
            try {
                this.getHibernateTemplate().save(transientInstance);
                log.debug("persist successful");
            } catch (RuntimeException re) {
                log.error("persist failed", re);
                throw re;
            }
        }
    
    ...
    
    }
    2,通过继承HibernateDaoSupport 使用SessionFactory.
    1. public class DAOSupportDAO extends HibernateDaoSupport {  
    2.     private static final Log log = LogFactory.getLog(DAOSupportDAO.class);  
    3.      
    4.     public void persist(Hbtest transientInstance) {  
    5.         log.debug("persisting Hbtest instance");  
    6.         try {  
    7.             this.getSessionFactory().getCurrentSession().save(transientInstance);  
    8.             log.debug("persist successful");  
    9.         } catch (RuntimeException re) {  
    10.             log.error("persist failed", re);  
    11.             throw re;  
    12.         }  
    13.     }  
    public class DAOSupportDAO extends HibernateDaoSupport {
        private static final Log log = LogFactory.getLog(DAOSupportDAO.class);
       
        public void persist(Hbtest transientInstance) {
            log.debug("persisting Hbtest instance");
            try {
                this.getSessionFactory().getCurrentSession().save(transientInstance);
                log.debug("persist successful");
            } catch (RuntimeException re) {
                log.error("persist failed", re);
                throw re;
            }
        }
    3,通过注入SessionFactory(推荐做法:好处是不会引入Spring的类)
    1. public class PlainHibernateDAO {  
    2.     private static final Log log = LogFactory.getLog(PlainHibernateDAO.class);  
    3.     private SessionFactory sessionFactory;  
    4.   
    5.     public void setSessionFactory(SessionFactory sessionFactory) {  
    6.         this.sessionFactory = sessionFactory;  
    7.     }  
    8.     public void persist(Hbtest transientInstance) {  
    9.         log.debug("persisting Hbtest instance");  
    10.         try {  
    11.             sessionFactory.getCurrentSession().save(transientInstance);  
    12.             log.debug("persist successful");  
    13.         } catch (RuntimeException re) {  
    14.             log.error("persist failed", re);  
    15.             throw re;  
    16.         }  
    17.     }  
    public class PlainHibernateDAO {
        private static final Log log = LogFactory.getLog(PlainHibernateDAO.class);
        private SessionFactory sessionFactory;
    
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
        public void persist(Hbtest transientInstance) {
            log.debug("persisting Hbtest instance");
            try {
                sessionFactory.getCurrentSession().save(transientInstance);
                log.debug("persist successful");
            } catch (RuntimeException re) {
                log.error("persist failed", re);
                throw re;
            }
        }
    对于事务的管理:

    1,显示的用Hibernate提供的 SessionFactory.getCurrentSession().beginTransaction(),commit,这时候

    hibernateProperties要配置hibernate.current_session_context_class=thread

    1. <SPAN style="COLOR: #000000">        <property name="hibernateProperties">  
    2.             <value>  
    3.                 hibernate.current_session_context_class=thread  
    4.                      
    5.             </value></SPAN>  
            <property name="hibernateProperties">
                <value>
                    hibernate.current_session_context_class=thread
                       
                </value>

    2,利用Spring的事务声明来做管理:hibernateProperties不能配置hibernate.current_session_context_class=thread 

    1. <tx:advice id="txAdvice" transaction-manager="txManager">  
    2.         <tx:attributes>  
    3.             <tx:method name="*" propagation="REQUIRED"/>  
    4.         </tx:attributes>  
    5.     </tx:advice>  
    6.   
    7.     <bean id="txManager"  
    8.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
    9.         <property name="sessionFactory" ref="mySessionFactory" />  
    10.     </bean>  
    11.   
    12.     <aop:config>  
    13.         <aop:pointcut id="persistOperation"  
    14.             expression="execution(* com.test.spring.hibernate.PlainHibernateDAO.*(..))" />  
    15.         <aop:advisor advice-ref="txAdvice" pointcut-ref="persistOperation" />  
    16.          
    17.     </aop:config>  
    <tx:advice id="txAdvice" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    
        <bean id="txManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="mySessionFactory" />
        </bean>
    
        <aop:config>
            <aop:pointcut id="persistOperation"
                expression="execution(* com.test.spring.hibernate.PlainHibernateDAO.*(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="persistOperation" />
           
        </aop:config>

  • 相关阅读:
    Linux Kernel 'b43'无线驱动本地特权提升漏洞
    Linux Kernel “dispatch_discard_io()”RO Disk Manipulation安全绕过漏洞
    Linux kernel ‘fill_event_metadata’函数资源管理错误漏洞
    Linux kernel ‘b43_request_firmware’函数格式化字符串漏洞
    phpcms 2007 onunload.inc.php update SQL注入漏洞
    出差到天津的计划
    Auguries of Innocence
    做一个东西要多久
    Wise Installation 9 的一个容易忽视的选项
    天津行总结路在嘴底下
  • 原文地址:https://www.cnblogs.com/kentyouyou/p/3146265.html
Copyright © 2020-2023  润新知