如何使用 Spring 数据 JPA 在 @Query 注释中动态传递列名 [英] How to pass column name dynamically inside a @Query annotation using Spring data JPA

查看:75
本文介绍了如何使用 Spring 数据 JPA 在 @Query 注释中动态传递列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的实体:

@Id
@Column_name = "abc"
int pk;
@Column_name = "def"
int id;

我的存储库为:

interface fetchDataRepository extends jpaRepository<className, int> {
    @Query("Select S_Test.nextVal from dual");
    Long generateId();
}

在上面的例子中,S_Test 是硬编码的序列名称.但问题是我想动态传递序列名称如下:

In above example S_Test is hardcoded sequence name. But the problem is that I want to pass sequence name dynamically as follows:

Long generateId(@Param("sequenceName") String sequenceName)

并在@Query注解中使用:

and use inside @Query annotation as:

@Query("Select :sequenceName.nextVal from dual");

有没有办法做到这一点?任何建议将不胜感激.

Is there anyway to do that? Any suggestion would be appreciated.

不能使用#(#entityName).如果是,请告诉我怎么做?

Isn't there possible to use #(#entityName). If yes, then please tell me how?

推荐答案

不幸的是,您只能替换在 JDBC 中可以做的事情(因此,几乎只是 INSERT 和 WHERE 子句中的值).不支持动态表、列、架构名称.

Unfortunately you can only substitute in things that you could do in JDBC anyway (so, pretty much just values in the INSERT and WHERE clauses). No dynamic table, column, schema names are supported.

有一个可能适用的例外情况,那就是 可以使用有限的 SpEL 子集.有一个可用的变量 - #entityName.因此,假设您的实体类上的 @Entity 注释与序列名称相同,您可以像这样使用 @Query:

There is one exception that may apply, and that is a limited subset of SpEL can be used. There is one variable available - #entityName. So, assuming that the @Entity annotation on your entity class is named identically to the sequence, you could use an @Query like so:

@Query("Select #{#entityName}.nextVal from dual");

否则,由于您的查询很简单并且不涉及任何对象关系映射,您可能需要 创建自定义存储库实现 并注入 JdbcTemplate 以运行查询.

Otherwise, since your query is simple and does not involve any object relational mapping, you would probably need to Create a custom repository implementation and inject a JdbcTemplate into it in order to run the query.

否则你可以注入一个 EntityManager 并尝试使用 JPA Criteria API - 但是您实际上并没有尝试将结果集映射到实体,因此 JdbcTemplate 会更简单.

Else you could inject an EntityManager and try using the JPA Criteria API - but again you arent actualy trying to map a resultset to an entity so JdbcTemplate will be simpler.

这篇关于如何使用 Spring 数据 JPA 在 @Query 注释中动态传递列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆