How to pass column name dynamically inside a @Query annotation using Spring data JPA

馋奶兔 提交于 2021-01-29 02:04:34

问题


I have entity like:

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

And I have Repository as:

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

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)

and use inside @Query annotation as:

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

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

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


回答1:


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.

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");

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.

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.



来源:https://stackoverflow.com/questions/57761631/how-to-pass-column-name-dynamically-inside-a-query-annotation-using-spring-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!