简体   繁体   English

JPA脱离结果

[英]JPA get detached result

My code: 我的代码:

String sql = SELECT * FROM users;

List<Users> users = entityManager.createNativeQuery(sql, Users.class); 

for(Users i : users) 
   entityManager.detach(i); 

How to replace this boilerplate loop: 如何更换样板循环:

for(Users i : users) 
   entityManager.detach(i); 

?

It is a simple example but imagine that every object has the 20 of neested objects then it would look like this: 这是一个简单的示例,但是假设每个对象都有20个所需的对象,那么它将看起来像这样:

for(Users i : users) 
{
       entityManager.detach(i); 
        for(Users y : i.getNeested()) 
        {
             entityManager.detach(y);
             for(Users y : i.getNames()) 
              ....
        }
}

Perform the query in a transaction by itself. 自己在事务中执行查询。 Once the transaction ends, the results won't be attached to the persistence context any more. 事务结束后,结果将不再附加到持久性上下文中。

Simple example, no separate detaching necessary. 简单的例子,不需要单独的分离。 Make sure to use a REQUIRES_NEW if you have an on-going transaction, otherwise they won't be detached. 如果您正在进行交易,请确保使用REQUIRES_NEW ,否则它们不会分离。

@Transactional(propagation=Propagation.REQUIRES_NEW)
@Override
public List<User> findUsers() {
    return em.createNativeQuery("SELECT * FROM users", User.class).getResultList();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM