Spring Boot版本:2.1.2.RELEASE
H2版本:1.4.197
通过 JpaRepository 查询:
@Repository
public interface PlayerStorage extends JpaRepository<Player, Long> {
List<Player> findByUid(@Param("uid") List<Integer> uid);
}
...
List<Player> foundByUids = playerStorage.findByUid(Arrays.asList(100, 200));
Spring 生成并执行查询:
Data conversion error converting "(100, 200)"; SQL statement:
select
player0_.id as id1_3_,
player0_.uid as uid3_3_
from
player player0_
where
player0_.uid=(100 , 200)
[22018-197]
...
Caused by: java.lang.NumberFormatException: For input string: "(100, 200)"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at org.h2.value.Value.convertTo(Value.java:1061)
H2 说:
DATA_CONVERSION_ERROR_1 = 22018
The error with code 22018 is thrown when trying to convert a value to a data type where the conversion is undefined, or when an error occurred trying to convert.
Example:
CALL CAST(DATE '2001-01-01' AS BOOLEAN);
CALL CAST('CHF 99.95' AS INT);
如果我尝试直接从 H2 Web 控制台执行此查询,我会得到相同的结果。如果我没猜错的话,问题出在语句中:player0_.uid=(100 , 200)
。与 in player0_.uid in (100 , 200)
相同的查询可以从 Web 控制台正常执行。
我还有 H2 的 spring boot 属性:
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.database=H2
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
最佳答案
错误可能出在存储库代码中:
public interface PlayerStorage extends JpaRepository<Player, Long> {
List<Player> findByUid(@Param("uid") List<Integer> uid);
}
来自documentation应该是:
public interface PlayerStorage extends JpaRepository<Player, Long> {
List<Player> findByUidIn(@Param("uid") List<Integer> uid);
}
另外:
- 如果Player中的字段为“uid”,则不需要@Param
- @Repository 也是多余的
- 我建议添加一些验证,确保传递给该方法的列表不为空,否则会导致异常。
关于java - Spring Boot H2数据转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54496461/