How To Update multi rows once in spring JPA?

Viewed 743

I use ICsvBeanReader to read CSV files. So what is the best workaround to update rows read from CSV file in the database without creating a new record if its id is new? I can't use

saveAll(Iterable)

because it will create a new record if it's id not found.

Example

    private Long id;
    private int quantity;
    private String name;

CSV File

id,quantity,name
1,30,name1
2,30,name2
20,30,name3
...

Note that:- row 20 is not found in the table so ignore it in an update.

2 Answers

JPA doesn't have an API to update an entity only if it exists, you can do a merge() which will update if the entity exists but it will also create a new row if it doesn't already exist.

Hibernate has an update() method which will update a row if it exists, but fail if the row doesn't exist.

I overcame this problem with a simple workaround. Fetch all table ids and check if CSV row id found in the table ids list so add this row to the new list else ignore this row. In final send the new list to saveall(iterable) method.

Related