我有一个 Emp 表和关联的 JPA 实体 - 员工。Emp 表具有 id、name 和 is_active 列。还有一个资产表,其中包含对 Emp 表的 FK 引用。资产表有 id、emp_id 和 name。
我想软删除(更新 is_active='N')员工,但使用读取的存储库方法删除关联的资产
public interface EmployeeRepository implements JpaRepository<Employee, Long>{
@Query(
nativeQuery = true,
value="BEGIN"+
" delete from assets where emp_id = :employeeId;"+
" update emp set is_active= 'N' where id = :employeeId;" +
"END"
)
public void inactivate(@Param("employeeId") Long employeeId);
}
上面的例子是为了说明目的。当我在我的应用程序实体上尝试类似的方法时,我从 Hibernate 类中收到错误。
PS:我知道还有其他方法,如 Hibernates 的级联功能等,但我对 Oracle 匿名块的使用特别感兴趣。
在 spring boot starter 数据 jpa 1.2.5 (hibernate 4.3.10)、oracle 12c 上测试。
不行:
@Modifying
@Query(value = "begin insert into T (ID,A) values (:id, :a); exception when dup_val_on_index then update T set A = :a where ID = :id; end;", nativeQuery = true)
void upsertWatchdog(@Param("id") Long id, @Param("a") Date a);
要么:
@Modifying
@Query(value = "begin insert into T (ID,A) values (?1, ?2); exception when dup_val_on_index then update T set A = ?2 where ID = ?1; end;", nativeQuery = true)
void upsertWatchdog(Long id, Date a);
作品:
@Modifying
@Query(value = "begin insert into T (ID,A) values (?1, ?2); exception when dup_val_on_index then update T set A = ?2 where ID = ?1 ; end;", nativeQuery = true)
void upsertWatchdog(Long id, Date a);
要么:
@Modifying
@Query(value = "begin insert into T (ID,A) values (:id, :a); exception when dup_val_on_index then update T set A = :a where ID = :id ; end;", nativeQuery = true)
void upsertWatchdog(@Param("id") Long id, @Param("a") Date a);
要么:
@Modifying
@Query(value = "begin insert into T (ID,A) values (?, ?); exception when dup_val_on_index then update T set A = ? where ID = ?; end;", nativeQuery = true)
void upsertWatchdog(Long id, Date a, Long id2, Date a2);
关键部分是在命名/定位参数和分号之间使用空格,因为 hibernate 将命名/定位参数名称视为id;而不是id。
但我不确定它是否有效,因为它是一个功能还是因为它是一个错误;-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句