gpt4 book ai didi

java - JPA 查找方法持久化数据

转载 作者:行者123 更新时间:2023-11-29 03:04:31 25 4
gpt4 key购买 nike

我正在使用 spring jpa。我已经使用

实现了事务管理
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'find' are read-only -->
<tx:method name="find*" read-only="true" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut id="transactionalServiceOperation"
expression="execution(* com.test..*ServiceImpl.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionalServiceOperation" />
</aop:config>

最近我注意到,虽然在某些情况下事务管理是有效的,但在其他情况下却不是。例如,我在服务方法中有这段代码,该方法由 @org.springframework.transaction.annotation.Transactional 注释。 方法里面的代码

guardianService.save(newFather);
parentsSet.add(newFather);
Guardian oldMother = guardianService.findById(motherId);

在上述情况下,数据库中的数据不会保留到第 3 行。一旦应用程序执行完第 3 行,newFather 的数据就会提交到数据库,即使应用程序在第 3 行之后生成异常也是如此。

guardianService.findById(motherId)的代码片段

@Override
public Guardian findById(long guardianId) {
return guardianRepository.findByGuardianId(guardianId);
}

GuardianRepository 内部

public interface GuardianRepository extends JpaRepository<Guardian, Long> {

Guardian findByGuardianId(long id);
}

guardianService.save(newFather);的代码片段

@Override
@Transactional
public Guardian save(Guardian guardian) {
return guardianRepository.save(guardian);
}

所以我的问题是 find() 方法是否以某种方式调用了 flush()commit()

最佳答案

find() 方法实际上调用了 flush 方法。默认情况下,在 JPA 中,FlushModeType设置为 AUTO ,这意味着如果发生对数据库的查询,数据库中的数据必须是当前事务的最新数据。根据定义:

When queries are executed within a transaction, if FlushModeType.AUTO is set on the Query object, or if the flush mode setting for the persistence context is AUTO (the default) and a flush mode setting has not been specified for the Query object, the persistence provider is responsible for ensuring that all updates to the state of all entities in the persistence context which could potentially affect the result of the query are visible to the processing of the query.

关于java - JPA 查找方法持久化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32719095/

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