gpt4 book ai didi

java - 事务性保存而不调用更新方法

转载 作者:IT老高 更新时间:2023-10-28 13:04:42 25 4
gpt4 key购买 nike

我有一个用@Transactional 注释的方法。我从我的 Oracle DB 中检索一个对象,更改一个字段,然后从该方法返回。我忘了保存对象,但发现数据库无论如何都会更新。

应用程序上下文

<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.

关于java - 事务性保存而不调用更新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8190926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com