当由 Spring/Hibernate JPARepository 返回时

如果我有一个存储库:


public interface ThingRepository extends JpaRepository<Thing, UUID> {

  @Query(/* query to get some Things */)

  Collection<Thing> getSomeThings(/* some arguments */);

}

哪个是由 Spring/Hibernate 自动装配的,Thing返回的实体对象将处于什么状态(持久/分离/瞬态/等)?


上下文 - 如果我们对返回的Thing(EG thing.setThingString("stuff!"))进行更改,是否存在将这些更改持久化回数据库而不显式调用的情况thingRepository.save(thing);?


鸿蒙传说
浏览 170回答 2
2回答

跃然一笑

一切都与事务边界有关。如果您的方法在任何事务之外被调用,则底层 entityManager 已经关闭并且返回的实体已分离。如果您的方法在现有事务中被调用,则 entityManager 仍处于打开状态并且返回的实体处于托管状态。请注意,在这种情况下,如果事务被标记为只读,则 entityManager 将永远不会被刷新,即使实体被管理,也不会保留任何修改。另请注意,内部逻辑事务属性不会覆盖readOnly 标志(与 rollbackFor 相反)public class A {&nbsp; &nbsp; @Transactional(propagation = Propagation.REQUIRED)&nbsp; &nbsp; public void performA() {&nbsp; &nbsp; &nbsp; &nbsp; // b transaction scope is not read only, but TransactionManager will rollback for checkedException thrown from here&nbsp; &nbsp; &nbsp; &nbsp; b.performB();&nbsp;&nbsp; &nbsp; }}public class B {&nbsp; &nbsp; @Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = CheckedException.class)&nbsp; &nbsp; public void performB() {&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java