在Spring Data JPA字段错误中使用Projections

时间:2017-10-27 18:52:16

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

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

我的存储库:

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

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

  

无法编写JSON:无法将类型[java.lang.String]转换为类型[int]以获取值&#39; hihi&#39;;
  嵌套异常是java.lang.NumberFormatException:对于输入字符串:\&#34; hihi \&#34 ;;
  嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:无法将类型[java.lang.String]转换为类型[int]以获取值&#39; hihi&#39;;
  嵌套异常是java.lang.NumberFormatException:对于输入字符串:\&#34; hihi \&#34;

     

(通过参考链:
  skay.model.api_searchuser [\&#34;结果\&#34;] - &GT; java.util.ArrayList中[0] - &GT; com.sun.proxy $ Proxy87 [\&#34;用户ID \&# 34;])`

如果我将界面中的类型getUserid();更改为String此错误已完成并且有一个新的json。

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

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

1 个答案:

答案 0 :(得分:1)

尝试使用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