'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);
}
Solution 1:[1]
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()
Solution 2:[2]
Use flush between deleteall and save.
Solution 3:[3]
Heey Warriors,finally this works for me.
@Modifying(flushAutomatically = true)
@Transactional
void deleteByProjet(Projet projet);
Good Luck ;)
Solution 4:[4]
I just changed from deleteAll
to deleteAllInBatch
(JpaRepository
interface) and it worked.
deleteAllInBatch
results in Hibernate registering a prepared statement delete from yourtable
right when deleteAllInBatch
is called.
With deleteAll
, Hibernate
- select all your data into memory, as entities
- for each entity, it calls EntityManager.delete
- each delete generates a
EntityDeleteAction
which will be called when transaction ends and session flushes. But for whatever reason, the actions for the inserts end up being called before the deletes (maybe the order is unpredictable, I'm not sure).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | runtime_expection |
Solution 2 | user5542464 |
Solution 3 | soufiane ELAMMARI |
Solution 4 | Tonsic |