关于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了

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