Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data: DeleteAll and Insert in same transaction

I am trying to achieve below native query logic using hibernate (Spring JPA). But save(Iterable) throws exception and rollback the entire transaction if one of the record fails to persist. Is there any way to do to catch the record error and proceed with insertion on other records.

eg:-

Native Sql Query

set autocommit=false
delete from EMPLOYEE;
insert into EMPLOYEE(id, name, sal) values(2, ‘Roy’, ‘rt’); —-stmt1
insert into EMPLOYEE(id, name, sal) values(2, ‘Joe’, 3000);
commit;

Note: sal column is numeric in EMPLOYEE table. Execution continues eventhough stmt1 failed.

Hibernate (CrudRepository)

@Autowired
CrudRepository employeeRepository;

@Transactional
public void saveToDB(List dataList) {
   employeeRepository.deleteAll();
   employeeRepository.save(dataList);
}
like image 746
Shameer Avatar asked Jul 15 '26 05:07

Shameer


2 Answers

Anyone else stumbling upon this problem. I managed to get it work with writing own deleteAll Method in RepositoryInterface and setting annotation like this:

@Modifying(flushAutomatically = true)
@Query("delete from MyEntity")
void deleteAllCustom()
like image 163
runtime_expection Avatar answered Jul 18 '26 08:07

runtime_expection


Use flush between deleteall and save.

like image 42
RKT Avatar answered Jul 18 '26 10:07

RKT