Search code examples
javahibernatejpaentitymanagerstateless

Reattaching and manipulating a detached instance in Hibernate (JPA)


I use stateless transactional services (meaning, I open a new session and transaction for every call) like this:

@Transactional
void someService(Object o) {
    Object newO = entityManager.merge(o);
    newO.getChildren().add(something);
}

The Object o which I pass to the service is a detached object. The problem with merge(object) is, that it returns a new instance to manipulate, instead of making the argument itself persistent. So any changes I make on the persistent object are not happening to the original object in memory.

I could of course rewire all my local references, but I am hoping there is a better solution.

Is there a way to make my local instance managed, instead of getting a new instance?

I tried refresh(object) and update(object) but I do get exceptions because the associations of the object are still detached.

When I annotate the associations with @Cascade(value=CascadeType.save-update) it works fine, but doesn't that cause performance issues when I have a lot of OneToMany or ManyToMany associations?


Solution

  • I think you can just use the detached Object o and after just to use the session.update(o).

    Try to watch this video tutorial, maybe it will be useful!

    Ciao!