简体   繁体   中英

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:

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:

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.

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).

First you don't need to add a @Query to make projections work. Just having the UserProjection as the return type of the method in repository should be enough. More about this here

Secondly, you can just have the following method in your repository as a projection-based findAll method;

public List<UserProjection> findAllProjectedBy();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM