首页 > 解决方案 > 如何在 Spring JPA 原生查询中替换 SQL 查询条件

问题描述

我有一个 spring jpa 本机查询(实际查询连接了多个表),如下所示。

@Query(nativeQuery = true, value="
select id, name from TABLE where id NOT IN ('2', '3')")
List<Object> getValueForNOTIN()

@Query(nativeQuery = true, value="
select id, name from TABLE where id IN ('4', '5')")
List<Object> getValueForIN()

而不是 2 种方法,我想使用一种方法,用这个“replaceClause”值替换 NOT IN 和 IN。

List<Object> getValueForBoth(@Param("replaceClause)" String replaceClause)

我在服务器启动时出错。我不能这样吗?

标签: springjpanative

解决方案


您可以使用静态字符串,例如

private String SELECT_NOT_IN_QUERY = "选择 id,从 TABLE 中选择名称,其中 id NOT IN ('id1', 'id2')"

private String SELECT_IN_QUERY = "select id, name from TABLE where id IN ('id1', 'id2')"

然后查找 id1 和 id2 并替换为它的值。相应地使用正确的静态字符串。


推荐阅读