简体   繁体   中英

How to avoid java.util.ConcurrentModificationException in entity merging in JPA and Hibernate

I'm using Spring MVC + Hibernate + JPA in this application. What I need to do is, update an entity(User) which is related with @manyToMany relationship with another entity(Task). Here is my code,

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);

Here I need to add new tasks to a user . But when I run this request, I'm getting java.util.ConcurrentModificationException

I tried to use Iterator instead of using for-each loop. But same result. In another way I tried using a separate List to adding old and new tasks instead of using a same list as above. But when I call entityManager.merge(user); It deletes existing task and re-add both old and new tasks. What I need to do to avoid getting this exception?

I appreciate your help, because I'm new to jpa .

Try changing this:

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

to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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