java - 在 Spring Data JPA 字段中使用投影错误

标签 java hibernate spring-mvc jpa spring-data-jpa

我是java Spring的新成员,今天尝试使用JPA的CrudRepository进行查询。我使用投影

我的存储库:

@Repository
public interface UserRepositoty extends CrudRepository<tbl_user, Integer> {
// search by username
@Query(value = "select (select l.state from tbl_request_love l where l.senderid = u.userid) as state, u.userid as userid,u.username as username,u.nickname as nickname,u.avatar as avatar"
        + " from tbl_user u"
        + " where u.username LIKE CONCAT('%',:username,'%') and u.coupleid is null" , nativeQuery = true)
List<tbl_user_search> findByUsernameEndWith(@Param("username") String username);
}

我的界面:

public interface tbl_user_search {
int getUserid();
String getUsername();
String getNickname();
String getAvatar();
String getState();
}

当我测试时,我收到此错误:

Could not write JSON: Failed to convert from type [java.lang.String] to type [int] for value 'hihi';
nested exception is java.lang.NumberFormatException: For input string: \"hihi\";
nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type [java.lang.String] to type [int] for value 'hihi';
nested exception is java.lang.NumberFormatException: For input string: \"hihi\"

(through reference chain:
skay.model.api_searchuser[\"result\"]->java.util.ArrayList[0]->com.sun.proxy.$Proxy87[\"userid\"])`

如果我将界面中的类型 getUserid(); 更改为 String,则会完成此错误并获得新的 json。

{
    "state": "Hi",
    "username": "https://forumhumgeduvn.000webhostapp.com/5skay/man.png",
    "userid": "Hi Hi",
    "avatar": "Pending",
    "nickname": "3"
}

但是 json 没有按顺序返回字段。我认为这是我的错误的问题。但我不知道解决它。你可以分享任何解决方案给我。谢谢!

最佳答案

尝试像这样使用LIKE:

" where u.username LIKE %:username% and u.coupleid is null"

或:

" where u.username LIKE %?1% and u.coupleid is null"

阅读此内容 Using advanced LIKE expressions

关于java - 在 Spring Data JPA 字段中使用投影错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46981678/

相关文章:

java - 这个程序中的 ArrayList 如何在没有任何循环的情况下打印元素?

java - 如何在 clojure project.clj 中排除storm-core jar

java - 如何在java中使用可以在任何计算机上运行的数据库

java - 每个 Namedcache 的 Coherence 分布式缓存过期

mysql - 用于维护记录草稿副本的数据库设计模式

javascript - AJAX 调用未将数据发送到 Controller 方法

java - 使用 @PathVariable 重定向到另一个 Controller

java - 在 google.Internal 服务器错误中添加联系人时出现异常

spring - RedirectView 不使用位置的相对路径

java - 通过 Spring + Hibernate 只读数据