0

Is there some fancy way to make a "differential" update on a list of rows in Spring? For instance, I have such rows in my database:

  • Row A
  • Row B
  • Row C

I am provided with a new set of items:

  • Row A
  • Row C
  • Row D

What I want to have as a result is:

  • Row A (updated, not removed and added)
  • Row C (updated, not removed and added)
  • Row D (added)
  • deleted row B

It is crucial here to keep track of creation and modification dates. Is there some convenient way to achieve this in Spring?

Thank you in advance for any tips.

SOLUTION:
I haven't found a "nice" way to do this. In the end I added Date fields with @CreationTimestamp and @UpdateTimestamp (though the latter could be a simple Date/LocalDate field). While uploading a new set, for each row I checked if repository didn't have such object already (had to be done by comparing all fields but ID since ID was auto-generated and I needed comparison by values - fortunately each combination of values in my system is unique). If it did, the update date was changed to current date. After this was done I simply deleted entities with update date prior to current date. Not a fancy way and quite slow but it works well.

centydev
  • 1
  • 3

2 Answers2

0

if you're using Entities you can use Spring CRUD Repositories. They have a method called save() that receives a list of entities. If the ID of any entity already exists, the repository will update it, otherwise it will create a new record in database.

You can take a look at Spring documentation here.

Please let me know if the post is useful for you.

  • Thanks for your reply! I use CRUD repositories extensively, but method save() doesn't delete the rows that do not appear in the new list. – centydev Jul 10 '17 at 15:24
  • Probably you'll need to implement your own functionality if your want to include the deletion functionality...unless your database table represents a key-value pair...if that's the point you can check this post: https://stackoverflow.com/questions/7525320/how-to-add-a-mapstring-person-in-an-entity-class With @CollectionTable JPA adds, deletes or updates the data in the appropiate case. – Andrés Felipe Pedraza Infante Jul 10 '17 at 20:41
0

If you're using EntityManager from JPA you can use entityManager.merge(yourEntity), this query will add new row if id's don't correspond to your database id or it will update your fields in the other way.

Also there are common methods from Session (its hibernate SessionFactory), there are method session.saveOrUpdate(yourEntity)

yevhensh
  • 390
  • 2
  • 3
  • 14
  • Thank you for your reply! However, as far as I am concerned, both of these do not delete rows which don't appear in the new list. Please correct me if I'm wrong. – centydev Jul 10 '17 at 15:23