OneToMany update. Delete always after insert in Hibernate

I have 3 tables with 3-level OneToMany relationships.

Now I am trying to delete one record in table B and re-insert a new record with the same name, same parent, and new table C records in one action using hibernate. The duplicate key error is thrown because of Hibernate insert first behavior. I have already read this post so I think I may be misused hibernate.

What is the best practice for my case?

Can’t you just flush the persistence context before doing the insert by using EntityManager.flush/Session.flush?

I have not to try to do it but I think I can flush before insert. I just confuse because I get the message from the post: “usually wanting to delete then reinsert is a sign that you are trying to use Hibernate in the wrong way.”

So should I consider that is a special case so Hibernate without querying is not suitable to handle this case?

Well if you think about it, it’s unnecessary to delete the object in the first place if you are going to re-insert it later anyway. IMO you should just update the existing object rather then deleting and re-inserting.

Well… I am not trying to re-insert.

In my table structure, the unique key is preventing the same name appear in my system. For my system user, he just deletes an old record and creates a new record with the same name in one action. The new record in table B might be one-to-many the new table C records.

Sorry for my bad English presentation but I think it’s definitely a new record…

I undestand that, but in your code, rather than doing oneToMany.remove(..) and oneToMany.add(...) you should be doing something like this oneToMany.stream().filter(..).findFirst().orElse(() -> {T elem = new T(); oneToMany.add(elem); return elem; }) which will retain the same object in the one-to-many association.

1 Like

Thanks, I think that is a solution for technical only. However, I think it is not the best solution because it is mismatched the user’s action in my DB. I mean the user action is definitely deleted one and then create a new one, but we are trying to replace the old one. Anyway thanks beikov.

I agree that Hibernate could try to do better here, but it is what it is right now. You’re welcome