Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling collection updates with JPA

I have a collection of custom objects and I'd like to persist it in the easiest way using JPA.

My CustomObject class is mapped to a table. Now I'm wondering if JPA provides some kind of utility to handle object collection.

In particular I'd like to add or remove objects to/from my collection and then pass to a save(Collection<CustomObject> cco) method without checking which objects have changed (which of them I need to add and which to remove...)

Is it possible?

like image 278
davioooh Avatar asked Sep 16 '25 01:09

davioooh


1 Answers

If you are looking for something in EntityManager which will save or update a collection, the answer is no. You will have to loop and do a save or update.

If you use EntityManager.merge() API it will update if record is existing or else will insert a new record.

As far as delete is concerned, how will JPA or any other ORM determine that you want to delete that instance, if its a soft delete like updating a column like is_active to true/false, then yes by calling merge it can be done, but if you want a hard delete then JPA won't be able to determine by itself, you will have to do it manually.

like image 84
mprabhat Avatar answered Sep 18 '25 13:09

mprabhat