繁体   English   中英

是否可以在 Spring 数据 JPA 存储库的 @Query 注释中使用 Oracle 匿名块?

[英]Is it possible to use Oracle Anonymous Block within the @Query annotation of Spring Data JPA Repository?

我有一个 Emp 表和关联的 JPA 实体 - 员工。 Emp 表有 id、name 和 is_active 列。 还有一个 Assets 表,它具有对 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 启动启动数据 jpa 1.2.5(休眠 4.3.10)、oracle 1.2 上测试。

不行:

@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

但我不确定它是因为它是一个功能还是因为它是一个错误;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM