如何避免JPA和Hibernate中实体合并中的java.util.ConcurrentModificationException

时间:2017-02-15 17:42:44

标签: java spring hibernate jpa jpa-2.0

我在此应用程序中使用Spring MVC + Hibernate + JPA。我需要做的是,更新与另一个实体(任务)的@manyToMany关系相关的实体(用户)。这是我的代码,

User user = baseRequest.getUser();

if (user.getTasks() != null && user.getTasks().size() > 0) {
    // Get logged user by userId
    User loggedUser = em.find(User.class, user.getUserId());

    //Get existing tasks for loggedUser
    List<Task> existingTasks = loggedUser.getTasks();

    //Get new tasks for user by request
    List<Task> tasks = user.getTasks();

    for (Task t : tasks) {
        // Look up new tasks by taskId
        task = em.find(Task.class, t.getTaskId());
        if (task != null) {
            if(!existingTasks.contains(task)){
                existingTasks.add(task);
            }
        }else{
            throw new SfaCustomException(String.format("taskId is required"));
        }
    }           
    user.setTasks(existingTasks);
}
entityManager.merge(user);
entityManager.flush();
entityManager.refresh(user);

我需要在用户中添加新的任务。但是,当我运行此请求时,我收到了java.util.ConcurrentModificationException

我尝试使用Iterator而不是使用for-each循环。但结果相同。换句话说,我尝试使用单独的List来添加旧任务和新任务,而不是使用与上面相同的列表。但是当我调用entityManager.merge(user);时,它会删除现有任务并重新添加旧任务和新任务。我需要做些什么才能避免出现此异常?

感谢您的帮助,因为我是jpa的新手。

1 个答案:

答案 0 :(得分:7)

尝试更改此内容:

dim lRow A Long, i as Long '<--| expliciltly declare each variable and use Long for row index ones since they can exceed Integer capacity
dim rngValues as Variant '<--| declare rngValues as a Variant instead as an array of Variant

rngValues = Application.Transpose(ThisWorkbook.Sheets(2).Range("C2:C" & lRow).Value) '<--| transpose the "columned" values to "rowed" ones suitable for a 1D array

For i = LBound(rngValues) To UBound(rngValues)
    Debug.Print Format(rngValues(i),"yyyy/mm/dd")
Next

到此:

//Get existing tasks for loggedUser
List<Task> existingTasks = loggedUser.getTasks();