hibernate - How to handle DataIntegrityVilolationException while saving a list in Spring Data JPA? -
i using spring data jpa in spring boot application, mysql. there saving list of entities unique constraint on field. out of list of entities, there 1 entity throw dataintegrityviolationexception due unique constraint. noticed none of entities persisted in case, not violate unique constraint. should ideal approach in case entities not violate unique persisted ? of course can iterate list , save them 1 one. in fact simplejparepository doing underneath.
@transactional public <s extends t> list<s> save(iterable<s> entities) { list<s> result = new arraylist<s>(); if (entities == null) { return result; } (s entity : entities) { result.add(save(entity)); } return result; }
my code - entity :
@entity @table(uniqueconstraints = @uniqueconstraint(columnnames={"name"},name="uq_name")) public class samplecontent { @id @generatedvalue private long id; private string name; //getter setters
}
repository :
public interface samplecontentrepository extends jparepository<samplecontent, serializable>{
}
junit test :
@test public void testcreate(){ list<samplecontent> samplecontentlist = new arraylist<>(); samplecontent samplecontent1 = new samplecontent(); samplecontent1.setname("dd"); samplecontent samplecontent2 = new samplecontent(); samplecontent2.setname("roy"); samplecontent samplecontent3 = new samplecontent(); samplecontent3.setname("xx"); samplecontentlist.add(samplecontent1); samplecontentlist.add(samplecontent2); samplecontentlist.add(samplecontent3); try{ this.samplecontentrepository.save(samplecontentlist); }catch(dataintegrityviolationexception e){ system.err.println("constraint violation!"); } }
there entity name "roy" present in table. so, entire transaction fails , @transactional rolls back.
i think can use next steps:
- load existing entities db set
- override
equals
,hashcode
methods based onname
- call
set::addall
antities (or add them 1 one) - save
set
db
maybe it's suboptimal because forces make select *
query. think it's more effective saving entities 1 one db.
accotding this article can use name business key, has lots of benefits.
Comments
Post a Comment