[英]How can we implement custom find methods in CrudRepository to get only specific columns from a database?
I have to execute a SQL query in my repository:我必须在我的存储库中执行 SQL 查询:
public interface UserRequestResponseRepository extends JpaRepository<UserRequestResponse, Integer> {
//public static final String FIND_QUERY = "select user.u_httpstatus ,user.u_queryparam from UserRequestResponse user";
public static final String FIND_QUERY =
"select new com.abc.datacollection.entity.UserRequestResponse(user.u_httpstatus ,user.u_queryparam) from UserRequestResponse user";
@Query(value = FIND_QUERY)
public List<UserProjection> getAllRequestResponseRecords();
}
where UserProjection is a projection that I defined:其中 UserProjection 是我定义的投影:
public interface UserProjection {
String getU_httpstatus();
String getU_queryparam();
}
The class userRequestResponse has more fields than u_httpstatus and u_queryparam, but I want only these 2 fields in my response. class userRequestResponse 的字段比 u_httpstatus 和 u_queryparam 多,但我的响应中只需要这两个字段。
public @ResponseBody List<UserRequestResponse> getAllRequestResponseRecords() {
return userRequestResponseRepository.findAll() ;
}
how do I modify the above code (findAll()) to get results from my custom query and not the results from the default CrudRepository findAll() (which returns all the fields).如何修改上述代码 (findAll()) 以从我的自定义查询中获取结果,而不是从默认 CrudRepository findAll() (返回所有字段)中获取结果。
First you don't need to add a @Query
to make projections work.首先,您不需要添加@Query
来进行预测。 Just having the UserProjection
as the return type of the method in repository should be enough.只需将UserProjection
作为存储库中方法的返回类型就足够了。 More about this here更多关于这里
Secondly, you can just have the following method in your repository as a projection-based findAll method;其次,您可以在存储库中使用以下方法作为基于投影的 findAll 方法;
public List<UserProjection> findAllProjectedBy();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.