Ant*_*edo 10 jpa jpa-2.0 spring-data-jpa jpa-2.1
使用spring数据JPA,我试图进行这种查询(它更复杂,这是一个简单的例子)
@Query(nativeQuery = true,
value = "SELECT * FROM events WHERE typeId IN (?1)")
List<Event> findEventsByType(List<Integer> types);
Run Code Online (Sandbox Code Playgroud)
当我启动查询时,异常会引发:
org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.util.ArrayList. Use setObject() with an explicit Types value to specify the type to use.
Run Code Online (Sandbox Code Playgroud)
我已经尝试了List <Integer>,Integer [],Object []和String但它不能正常工作......
我不能通过值列表吗?
进行此类查询的最佳方法是哪种?
谢谢!
小智 12
尝试删除@Query并创建方法名称:
public List<Event> findByTypeIn(List<Integer> types);
Run Code Online (Sandbox Code Playgroud)
见链接中的表2.2:http://docs.spring.io/spring-data/jpa/docs/1.2.0.RELEASE/reference/html/
小智 6
@Query(value = "SELECT c from Company c where " +
"c.companyName IN (:company_names)")
List<Company> findCompaniesByName(@Param("company_names") List<String> companyNames);
Run Code Online (Sandbox Code Playgroud)
这就是您问题的解决方案。
在这里,我传递包含公司名称的列表,我正在查询数据库并将结果存储在列表中。
希望这有帮助!
使用 JPQL。本机查询是或应该完全按照您创建的 SQL 字符串传递到数据库,除非您的驱动程序可以采用序列化集合并了解单个参数需要解释为多个参数,否则它将无法工作。您传入的集合需要根据集合中元素的数量将 SQL 从 (?) 扩展为 (?, ?,...),而 JDBC 驱动程序无法做到这一点,而 JPA 提供程序则需要按原样执行字符串。
JPQL 查询允许 JPA 提供程序根据传入的列表动态创建所需的 SQL,因此它可以为您扩展集合。
我试过如下,它对我有用。
@Query(value = "select * from events where type_id in :types", nativeQuery = true)
List<Event> findEventsByType(@Param("types") List<Integer> types);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19487 次 |
| 最近记录: |