加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 事务性保存而不调用update方法

发布时间:2020-12-15 07:38:55 所属栏目:Java 来源:网络整理
导读:我有一个使用@Transactional注释的方法.我从Oracle DB中检索一个对象,更改一个字段,然后从该方法返回.我忘了保存对象,但发现无论如何都要更新数据库. 的applicationContext tx:annotation-driven /bean id="transactionManager" class="org.springframework.
我有一个使用@Transactional注释的方法.我从Oracle DB中检索一个对象,更改一个字段,然后从该方法返回.我忘了保存对象,但发现无论如何都要更新数据库.

的applicationContext

<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

我的方法

@Transactional
public void myMethod(long id) {
    MyObject myObj = dao.getMstAttributeById(id);
    myObj.setName("new name");
    //dao.update(myObj);
}

我的问题是为什么MyObject被持久化到数据库?

解决方法

因为hibernate会自动检测对持久性实体所做的更改并相应地更新数据库.这种行为记录在 chapter 11的hibernate参考手册中.相关部分如下:

Hibernate defines and supports the following object states:

  • Transient – an object is transient if it has just been instantiated using the new operator,and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).

  • Persistent – a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded,however,it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements,or DELETE statements when an object should be made transient.

  • Detached – a detached instance is an object that has been persistent,but its Session has been closed. The reference to the object is still valid,of course,and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time,making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions,i.e.,a unit of work from the point of view of the user.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读