I am using JPA to make an insert into my POSTGRES db. I recently added a Unique key constraint on one of the tables. The table looks like this:
______________________________________________
|Id| Action| Actor| Assignee| Date| Team|
----------------------------------------------
Id is the primary Key and the combination of Action, Actor, Assignee and Date is an unique key. When I get the JSON object from the 3rd party API i use the following method to save the data into the database.
streamItemArray.parallelStream().forEach(streamItem -> {
try{
streamItemRepository.save(streamItem);
}catch(ConstraintViolationException e){
System.out.println("Issue with unique key");
System.out.println(e.getMessage());
}
catch (Exception e){
System.out.println("others");
System.out.println(e.getMessage());
}
});
the code ran for the first few time and now it is not running at all.
2017-07-31 15:14:04.811 WARN 7867 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23505
2017-07-31 15:14:04.812 ERROR 7867 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: duplicate key value violates unique constraint "Unique_key"
Detail: Key (action, actor, assignee, date)=(Dismissed, Karen William, Karen William, 2017-07-21 01:19:05 IST) already exists.
2017-07-31 15:14:04.812 INFO 7867 --- [nio-8080-exec-4] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
others
could not execute statement; SQL [n/a]; constraint [Unique_key]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
My question here is:
How do we handle duplicates when we insert into db using JPA?
When using the foreach statement, if one repository.save fails will it execute the next item in foreach or does it stop the complete execution there itself?
Thanks for your help in advance.