Handling collection updates with JPA

11,121

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.

Share:
11,121
davioooh
Author by

davioooh

Hi, I'm David Castelletti. I like to create things with Java & Kotlin (❤). LinkedIn profile Personal Page + Blog (italian)

Updated on June 26, 2022

Comments

  • davioooh
    davioooh almost 2 years

    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?

  • Fritz
    Fritz almost 12 years
    +1 The deleting part is the one that gets tricky, you should have some sort of metadata for your objects (or another list and maintain a relationship through the indexes) to know which ones should be updated and which ones should be deleted.
  • mprabhat
    mprabhat almost 12 years
    Yep, deletion cannot be done that easy, mapping has to be there somewhere :)