關於spring整合hibernate使用update無異常但沒有效果(不輸出sql語句)

單獨使用hibernate時

openSession()

在沒有使用spring控制事務時,使用的是sessionFactory.openSession()。這樣每個方法都會新建一個session,必須在方法中控制和關閉session。

於是一開始我直接在try-with-resource語句中使用session的update等方法,無任何事務,在單元測試時發現update方法和delete方法無效。

解決方法有兩種:

  • 加上事務控制: session.beginTransaction()和trans.commit()

  • 加上flush方法: session.flush()


getCurrentSession()

使用getCurrentSession創建的session會綁定到當前線程,並會在commit或rollback後自動關閉

使用currentSession,就必須使用事務管理


使用Spring事務管理

  1. 需要使用getCurrentSession獲取session
  2. 在操作中不要顯示的關閉session
  3. 不需要進行編碼式事務,使用聲明式事務

實例:

1. 在spring配置文件中添加如下代碼


    <!--hibernate事務-->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!--aop管理事務-->
    <aop:config>
        <aop:pointcut expression="execution(* wo.idao.*.*(..))" id="daoCut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="daoCut"/>
    </aop:config>

    <tx:advice transaction-manager="txManager" id="txAdvice">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>

此時的dao層只需要簡單的 session().update(entity)就行了。

再次單元測試,ok了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章