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