【问题标题】:Is it possible to use Oracle Anonymous Block within the @Query annotation of Spring Data JPA Repository?是否可以在 Spring Data JPA Repository 的 @Query 注释中使用 Oracle Anonymous Block?
【发布时间】:2020-11-28 14:16:03
【问题描述】:

我有一个 Emp 表和关联的 JPA 实体 - Employee。 Emp 表有 id、name 和 is_active 列。 还有一个 Assets 表,它具有对 Emp 表的 FK 引用。 Assets 表有 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 Anonymous Blocks 的使用特别感兴趣。

【问题讨论】:

  • 希望你喜欢这样的东西。stackoverflow.com/questions/5101529/…
  • @Sujitmohanty30...感谢您的链接...但我正在探索通过 Spring Data JPA 存储库方法使其工作。我知道我们可以通过 JDBC CallableStatement 实现相同的功能,但如果我可以通过 Query(或其他)注解实现它,我宁愿不编写 JDBC 代码。
  • 您找到解决方案了吗?

标签: oracle spring-data-jpa spring-data


【解决方案1】:

在 spring boot starter data 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

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

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2019-11-30
    • 2014-08-31
    • 2014-05-21
    • 1970-01-01
    • 2018-01-19
    • 2019-05-12
    • 2019-01-21
    • 2019-02-03
    相关资源
    最近更新 更多