Spring数据:DeleteAll和Insert在同一事务中

Sha*_*eer 5 java spring hibernate spring-data spring-data-jpa

我正在尝试使用 hibernate (Spring JPA) 实现以下本机查询逻辑。但是,如果其中一条记录无法持久保存,则 save(Iterable) 会引发异常并回滚整个事务。有什么方法可以捕获记录错误并继续插入其他记录。

\n\n

例如:-

\n\n

原生 SQL 查询

\n\n
set autocommit=false\ndelete from EMPLOYEE;\ninsert into EMPLOYEE(id, name, sal) values(2, \xe2\x80\x98Roy\xe2\x80\x99, \xe2\x80\x98rt\xe2\x80\x99); \xe2\x80\x94-stmt1\ninsert into EMPLOYEE(id, name, sal) values(2, \xe2\x80\x98Joe\xe2\x80\x99, 3000);\ncommit;\n
Run Code Online (Sandbox Code Playgroud)\n\n

注意:Sal 列在 EMPLOYEE 表中是数字。即使 stmt1 失败,执行仍会继续。

\n\n

Hibernate(CrudRepository)

\n\n
@Autowired\nCrudRepository employeeRepository;\n\n@Transactional\npublic void saveToDB(List dataList) {\n   employeeRepository.deleteAll();\n   employeeRepository.save(dataList);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

小智 8

其他人偶然发现这个问题。我设法通过在 RepositoryInterface 中编写自己的 deleteAll 方法并设置注释来使其工作,如下所示:

@Modifying(flushAutomatically = true)
@Query("delete from MyEntity")
void deleteAllCustom()
Run Code Online (Sandbox Code Playgroud)


小智 3

在deleteall和save之间使用flush。