Spring Boot H2数据转换

时间:2019-02-02 18:58:29

标签: java spring-data-jpa h2

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

弹簧生成和执行的查询:

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)。用的 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

2 个答案:

答案 0 :(得分:3)

可能,该错误是在存储库中的代码:

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

也:

  • 如果“UID”是在播放器中的字段,则不需要@Param
  • @Repository也是多余的
  • 我建议添加一些验证,以确保传递给该方法的列表不为空,否则将导致异常。

答案 1 :(得分:2)

尝试你的方法重命名为

List<Player> findByUidIn(@Param("uids") List<Integer> uids);