I use Spring + Hibernate + JPA
I need to insert the list of ORDER(maximum 60 or 70) . I do not want my processing to fail in case of duplicates.
Is it possible to do such bulk INSERT
in single transaction, catch/suppress exception for duplicates, proceed with INSERT
and commit the transaction? Or, is there no other way than transaction-per-INSERT pattern (or) merge (or) find the record based on Primary key and insert If no primarykey is found?
Currently, my transaction is always rolled back for DataIntegrityViolationException
, no matter how I configure noRollbackFor attribute for my transaction ( Transactional
annotation).
When 1 duplicate Record is inserted , it throws DataIntegrityVioalationException and while processing the next record it results
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
Here is the Unit of work :
for(Order order: OrderList) {
// Insert order into ORDER table
//If insert fails due to Duplicate key then no rollback and I follow steps 2 & 3.
//If insert fails due to any reason except duplicate key then rollback all the previous transactions
}
Here is my implemenation :
Service :
@Autowired
MyRepository repo;
@Transactional
@override
public void inserOrder(List<Order> orderList) {
try {
for(Order order: orderList) {
repo.insertOrderDao(order);
}
} catch(all duplicate key exceptions like entityExist, persist, ConstraintVioaltion, DataIntegrity e) {
// just log it and do nothing;
} catch(Exception e) {
e1.printStackTrace();
}
}
My Repositary :
@PersistentContext(unitNmae = "MY_SHCEMA")
EntityManager entityManager;
@Override
public void insertOrderDao(Order order) {
entityManager.persist(order);
entityManager.flush();
}