【问题标题】:Jpa Spring Boot error -> cannot convert object to type booleanJpa Spring Boot 错误 -> 无法将对象转换为布尔类型
【发布时间】:2022-08-14 22:14:32
【问题描述】:

您好,实际错误是:

Exception in thread \"main\" org.springframework.core.convert.ConversionFailedException: 

Failed to convert from type [java.lang.Object[]] to type [boolean] for value \'{2, ramesh, pass, 12345, ramu}\'; 

nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Integer] to type [boolean]

在这里,我尝试创建一种通过 id 查找用户的方法,但是当我尝试将值放入布尔类型时,它给出了上述错误

@Query(\"select case when count(s)>0 then true else false end from user_dao s where s.id =:id \")

@Query(value = \"select * from user_dao where id =:id \", nativeQuery = true)
boolean isStudentExistsById(@Param(\"id\") Integer id);

main 方法中 -> 这应该打印 true 或 false。

System.out.println(userRepo.isStudentExistsById(2));

在bean的构造函数中

    UserDao(int id, String name, String phone, String user_name, String 
    password) {
        
        
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.user_name = user_name;
        this.password = password;
    }
  • 错误是针对 Sysout 行
  • 您的请求select * from user_dao where id =:id 有一个user 用于响应,而不是boolean,您必须调整您的请求以使其选择boolean
  • 查询的响应是一个实体并且您表示是一个布尔值,您需要将布尔值更改为实体(您的 dao),或者更改您的查询以返回一个布尔值。

标签: spring spring-data-jpa


【解决方案1】:

最简单的方法 - CrudRepository 的使用方法(您的存储库通常继承它):

boolean existsById(Integer id)

其他选项见Spring Data JPA and Exists query

【讨论】:

  • 是的,实际上我更改了老师给我们的代码,他实际上通过了一个返回布尔值的查询,我现在将尝试使用 existsById 方法,因为他从未对此进行过探索
猜你喜欢
  • 2020-06-05
  • 2012-08-15
  • 2020-08-06
  • 2015-10-03
  • 2011-02-25
  • 2018-03-22
  • 2023-04-03
  • 1970-01-01
  • 2014-02-03
相关资源
最近更新 更多