spring4整合hibernate5以及出現的問題解決辦法


 每一次的學習,都是一小步一小步的進行的,學習語言,重要的是能把hello world寫出來

以及在學習過程中出現的問題能夠及時的記錄並總結

spring目前最新的版本是4.3,而hibernate是5.2

最新版本的學習是要花費很大的勇氣進行的

首先是互聯網上幾乎沒有什么資料可供參考

其次,這兩個框架在一些業務邏輯的處理方法上,和之前的版本有很大的不同

首先是hibernate,構建sessionfactory不再是3.5以前版本的老辦法了

下面是我的獲得sessionfactory方法

public static SessionFactory getSessionFactory()
    {
        SessionFactory sessionFactory = null;
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure().build();
        try
        {
            sessionFactory = new MetadataSources(registry).buildMetadata()
                    .buildSessionFactory();
        } catch (Exception e)
        {
            StandardServiceRegistryBuilder.destroy(registry);
        }
        return sessionFactory;
    }

spring是一個集大成者,可以很好的管理hibernate

再者。spring aop功能太強大了,利用切面編程可以方便的進行事務管理

spring中可以直接對hibernate進行配置,所以以前的hibernate.cfg.xml可以直接舍棄掉了

我們可以在spring配置文件中進行sessionFactory配置,dataSource配置以及事務配置

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />

此處注意在hibernate5里面,我們的sessionFactory由spring提供的org.springframework.orm.hibernate5.LocalSessionFactoryBean類進行實例化

dataSource進行數據源的定義

我們可以用c3p0進行數據緩沖池

 

添加事務支持

 

<!-- 配置Hibernate事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>


    <aop:config proxy-target-class="true">
        
        <aop:pointcut expression=" execution(* top.scorpion.service..*(..))"
            id="serviceMethod" />
        
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
    </aop:config>
    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        
        <tx:attributes>
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

這樣我們就可以利用spring管理hibernate了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM