在下面的类中,两个方法都返回相同的对象。
但是从第一个返回的对象列表是否被管理,因为它与事务的一部分相比,而第二个不是事务的一部分?
public class QueryServiceImpl implements QueryService {
@PersistenceContext(unitName="PC")
EntityManager em;
//default attribute
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public List findAlItems() {
return em.createQuery("SELECT item FROM Item item",
Item.class)
.getResultList();
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public List findAlItemsNoTransaction() {
return em.createQuery("SELECT item FROM Item item",
Item.class)
.getResultList();
}
答案 0 :(得分:1)
关于你的例子,你是对的。从第二个方法返回后,不应管理所有实体(findAlItemsNoTransaction)。但是,如果您想保持它们的管理,您应该使用:
@PersistenceContext(type=EXTENDED)
像JPA规范中所示:
/*
* An extended transaction context is used. The entities remain
* managed in the persistence context across multiple transactions.
*/
@Stateful
@Transaction(REQUIRES_NEW)
public class ShoppingCartImpl implements ShoppingCart {
@PersistenceContext(type=EXTENDED)
EntityManager em;
private Order order;
private Product product;
public void initOrder(Long id) {
order = em.find(Order.class, id);
}
public void initProduct(String name) {
product = (Product) em.createQuery("select p from Product p
where p.name = :name")
.setParameter("name", name)
.getSingleResult();
}
public LineItem createLineItem(int quantity) {
LineItem li = new LineItem(order, product, quantity);
order.getLineItems().add(li);
em.persist(li);
return li;
}
}