0

I have this requirement:

  • Csv Upload (using opencsv)
  • Should display if the record is inserted (if it doesn't exist in the db) or updated (if it exists). Eg.: 5 records inserted 2 records updated.

Usually I use repo.saveAll(entityObjList) to save all the entries.

Since I have to keep track of number of updates and inserts, I came up with using the repo.save(entityObj) method inside the for loop which is not greatly appreciated.

Is there any other way to approach this problem ? Any suggestion is welcome.

  • 1
    What does "which is not greatly appreciated" mean? Did you get some pushback from your team/corporate? What was the feedback? – Robert Harvey Jul 16 at 17:09
  • Most relational database systems will return the number of records affected from a query. Why don't you just fix your saveAll method so it returns that number? – Robert Harvey Jul 16 at 17:10
  • @RobertHarvey Well we decided not to use the JpaRepository.save() inside the for loop because of this. The JpaRepository.saveAll() seems to return the last saved object. It is not my implementation of the same. – iamL Jul 16 at 17:17
  • If you can't fix the saveAll method, you'll have to decide whether the performance or the number of records returned is more important. – Robert Harvey Jul 16 at 17:27
  • Do the entities have Ids generated by the database, or are you assigning Ids to new entities prior to saving? – Greg Burghardt Jul 16 at 17:54
0

Since the Ids of the entities are numeric and generated by the database on insert, loop over all of the entities. If the Id of an entity is 0 or null, then it will be an INSERT. If the Id of an entity is greater than zero (or what ever the minimum number of the sequence is) then it will be an UPDATE.

You would loop over the entities to be saved and tally up in the inserts and updates, then call the saveAll method on the repository, where you can get the performance boost over calling save for each entity individually.

Summing the inserts and updates might be better off in a service layer or class representing a use case, rather than the repository. The additional loop to detect the inserts and updates will add overhead, but you should be fine performance-wise until you reach the 1,000s of entities.

Even then, measure the performance to see if the decrease is small enough to make this feature worthwhile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.