Question

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?

Was it helpful?

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!

OTHER TIPS

You can use the find(entityClass, primaryKey) method to load your object. Just specify the primary key and the entity Class values and it returns a live object from the DB.

Now make your changes to this object and any changes made to this live object, will be reflected back and hibernate will update the database accordingly. I've personally faced such a situation and this worked for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top