简体   繁体   English

@Query注释和带引号的字符串中的命名参数

[英]@Query annotation and named parameters in quoted strings

So, here is the native MySQL query where I want to get all the rows based on JSON key-value pairs (ev_data is json type column), and it works just fine: 因此,这是本机MySQL查询,我想在其中获取基于JSON键值对(ev_data是json类型列)的所有行,并且工作得很好:

SELECT * FROM event WHERE JSON_CONTAINS(ev_data, '{"key":"key1","value":"val1"}','$.items')

An example of ev_data column content: ev_data列内容的示例:

{"items":[{"key":"key1","value":"val1"},{"key":"key2","value":"val2"}]}

Now, I am using Spring Boot's CrudRepository interface and @Query annotation for my custom fetch method as follows: 现在,我将Spring Boot的CrudRepository接口和@Query注释用于我的自定义提取方法,如下所示:

@Query(value="SELECT * FROM event WHERE JSON_CONTAINS(ev_data, '{\"key\" : \"key1\", \"value\" : :value}', '$.items')", nativeQuery=true)
Set<Event> findAllByItemKey1Value(@Param("value") String value);

This, however, won't work and trigger an exception like: java.lang.IllegalArgumentException: Parameter with that name [value] did not exist because, apparently, you are not allowed to use parameters (named or indexed) inside quoted strings . 但是,这将无法正常工作并触发如下异常: java.lang.IllegalArgumentException: Parameter with that name [value] did not exist因为显然, 您不允许在带引号的字符串中使用参数(命名或索引) Not sure if it's JPA/JPQL or Spring Boot thing but it is a fact. 不确定是JPA / JPQL还是Spring Boot,但这是事实。

The only workaround solution I have found so far is by using MySQL string REPLACE() function: 到目前为止,我发现的唯一解决方法是使用MySQL字符串REPLACE()函数:

@Query(value="SELECT * FROM event WHERE JSON_CONTAINS(ev_data, REPLACE('{\"key\" : \"key1\", \"value\" : \"*v*\"}','*v*', :value), '$.items')", nativeQuery=true)
Set<Event> findAllByItemKey1Value(@Param("value") String value);

It's not very elegant but it works for me and similar trick should also work for any named parameters used inside quotes. 它不是很优雅,但对我有用,类似的技巧也适用于引号内使用的任何命名参数。

Anyway, please let me know if you think this can be done better or more kosher , so to speak ;-) 无论如何,请告诉我您是否认为可以做得更好或更洁一点 ,-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM