# Can not commit bulk transaction on insert failure due to duplicate key error

**URL:** <https://discourse.hibernate.org/t/can-not-commit-bulk-transaction-on-insert-failure-due-to-duplicate-key-error/2521>\
**Category:** Hibernate ORM\
**Created:** [March 27, 2019, 5:56pm UTC](https://discourse.hibernate.org/t/can-not-commit-bulk-transaction-on-insert-failure-due-to-duplicate-key-error/2521 "2019-03-27T17:56:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alagammal](https://avatars.discourse-cdn.com/v4/letter/a/e47774/32.png) [@Alagammal](https://discourse.hibernate.org/u/Alagammal)\
**Post date:** [March 27, 2019, 5:56pm UTC](https://discourse.hibernate.org/t/can-not-commit-bulk-transaction-on-insert-failure-due-to-duplicate-key-error/2521/1 "2019-03-27T17:56:37Z")

</div>

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

```auto
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 :

```auto
@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 :

```auto
@PersistentContext(unitNmae = "MY_SHCEMA")
EntityManager entityManager;

@Override
public void insertOrderDao(Order order) {
     entityManager.persist(order);
     entityManager.flush(); 
}

```
