gpt4 book ai didi

java - 新事务是否分离所有以前的实体?

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:58 24 4
gpt4 key购买 nike

假设我们有以下代码:

@Entity
public class User {
@Id
private String name;
@OneToOne(cascade = CascadeType.ALL)
private Address address;
//getters and setters
}

@Entity
public class Address {
@Id
private int id;
private String street;
//getters and setters
}

@Stateless
//@Service
public class UserLogicClass {
@PersistenceContext
//@Autowired
private EntityManager entityManager;

public void logicOnUser(User user) {
if(logicOnAddress(user.getAddress()) {
otherLogicOnUser(user);
}
}

public boolean logicOnAddress(Address address) {
//
entityManager.find(address);//address becomes managed
//
}

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
//@Transactional(propagation = Propagation.REQUIRES_NEW)
public void otherLogicOnUser
//
entityManager.find(user);/*without annotation, user is not managed and address is managed, but with the transaction annotation is the address still managed?*/
//
}
}

问题依赖于最后一个方法的注释;我很好奇在 Spring 案例和 EJB 案例中会发生什么。假设 Spring 配置了 JTA 事务,并且从此类调用的任何方法都会启动一个新事务,就像在 EJB 中一样。

最佳答案

这更多是 JPA 的问题。 entityManager 不会传播到新事务,除非您对其进行扩展:

@PersistenceContext(type = PersistenceContextType.EXTENDED)
//@Autowired
private EntityManager entityManager;

引自 JPA 2.0 规范:

A container-managed persistence context may be defined to have either a lifetime that is scoped to a single transaction or an extended lifetime that spans multiple transactions, depending on the PersistenceContextType that is specified when its entity manager is created. This specification refers to such persistence contexts as transaction-scoped persistence contexts and extended persistence contexts respectively.

关于java - 新事务是否分离所有以前的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16249065/

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