简体   繁体   English

Spring Data JPA存储库查询 - 如何将@Param值映射到多个参数类型

[英]Spring Data JPA Repository Queries - How to map @Param value to multiple parameter types

I have implemented following JPA Repository query for some common search functionality. 我已经针对一些常见的搜索功能实现了以下JPA Repository查询。 But with that query, due to age is a Integer value and mapping Parameter is String value I got some exception as follow. 但是对于那个查询,由于age是一个整数值而映射参数是String值,我得到了一些例外,如下所示。 Is there any mechanism to implicitly casting parameter to relevant data type instead of we do that. 有没有任何机制可以隐式地将参数转换为相关数据类型而不是我们这样做。 Thanks. 谢谢。

Query with common parameter 使用通用参数查询

  @Query("select u from User u where u.firstname = :searchText or u.age = :searchText")
  List<User> findBySearchText(@Param("searchText") String searchText);

Exception 例外

Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: integer = character varying 
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

The issue you see has nothing to do with the binding itself. 您看到的问题与绑定本身无关。 Spring Data basically binds the value you give to the named parameter searchText . Spring Data基本上绑定了您为命名参数searchText提供的值。

It looks like what happens next is that your persistence provider builds some SQL from it where there's a type mismatch apparently. 看起来接下来发生的事情是你的持久性提供程序从中构建一些SQL,显然存在类型不匹配。 Age doesn't seem to be of type String , is it? 年龄似乎不是String类型,是吗? That said, I think trying to bind an arbitrary String to an integer (which it is I guess) is a very weird approach in the first place. 也就是说,我认为尝试将任意String绑定到一个整数(我猜是这样)是一个非常奇怪的方法。

SQL is not really built to support arbitrary text search features and schema is helping you to detect invalid criterias (which it does in this case). SQL并不是真正构建为支持任意文本搜索功能,而模式正在帮助您检测无效标准(在这种情况下它会执行)。 Have you thought about adding a full-text search store (Elasticsearch, Solr or the like) and do the text searches in those? 您是否考虑过添加全文搜索商店(Elasticsearch,Solr等)并在其中进行文本搜索?

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

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