我使用spring data jpa进行本机查询时遇到问题

时间:2019-06-19 05:36:56

标签: database spring oracle jpa

我有一个查询,可以从oracle db获取结果,但是当我将该查询用作spring数据jpa中的本机查询时。我收到异常,因为无效的表名

这是我正在运行的查询

SELECT listagg(COLUMN_TWO,' ') within group (order by COLUMN_TWO) 
FROM (select 'RDIFP' as val from dual union all
      select 'RDIFP' as val from dual union all
      select 'DROWM' as val from dual
     ) v left join
     TABLE_NAME_ONE 
     on v.val = COLUMN_TWO, TABLE_NAME_TWO, TABLE_NAME_THREE
WHERE 
COLUMN_THREE = COLUMN_FOUR AND  
COLUMN_FIVE = COLUMN_SIX AND 
COLUMN_ONE = '176134'

我正在下面的spring data jpa代码中使用它

static final String QUERY_VALUES =
            "SELECT listagg(COLUMN_TWO,' ') within group (order by COLUMN_TWO) 
FROM (:prQry) v left join
     TABLE_NAME_ONE 
     on v.val = COLUMN_TWO, TABLE_NAME_TWO, TABLE_NAME_THREE
WHERE 
COLUMN_THREE = COLUMN_FOUR AND  
COLUMN_FIVE = COLUMN_SIX AND 
COLUMN_ONE = '176134'";

@Query(value = QUERY_VALUES, nativeQuery=true)
String getValuesById(@Param("prQry") String prQry);

对于参数prQry,我将动态生成查询并将其存储在字符串中,并将其作为参数传递,因为我会将值传递为

String prQry= "select 'RDIFP' as val from dual union all
      select 'RDIFP' as val from dual union all
      select 'DROWM' as val from dual";

动态迭代后,我将像上面一样。

在实现它后,我将其作为无效的表名得到了例外。谁能在这个问题上帮助我以不同的方式使用它,或者我在代码中做错了什么。

1 个答案:

答案 0 :(得分:0)

不幸的是,您无法使用Spring Data Repositories来实现这一点,因为这些参数会转换为字符串,并且在FINAL查询中您拥有:

SELECT listagg(COLUMN_TWO,' ') within group (order by COLUMN_TWO)
FROM ("select 'RDIFP' as val from dual ... ") v

这将显示为字符串和无效查询。 @Param仅用于WHERE子句。

一种实现所需目标的方法是使用EntityManager:

@Autowired 
EntityManager entityManager;

static final String QUERY_VALUES =
        "SELECT listagg(COLUMN_TWO,' ') within group (order by COLUMN_TWO) 
            FROM (:prQry) v left join
                 TABLE_NAME_ONE 
                 on v.val = COLUMN_TWO, TABLE_NAME_TWO, TABLE_NAME_THREE
            WHERE 
            COLUMN_THREE = COLUMN_FOUR AND  
            COLUMN_FIVE = COLUMN_SIX AND 
            COLUMN_ONE = '176134'";

public String getValuesById(String prQry) {
    Query q = entityManager.createNativeQuery(QUERY_VALUES.replace(":prQry", prQry), String.class);
    return q.getSingleResult();
}

无论如何,这是更改FROM条件时动态查询的想法。