簡體   English   中英

我們如何在 CrudRepository 中實現自定義查找方法以僅從數據庫中獲取特定列?

[英]How can we implement custom find methods in CrudRepository to get only specific columns from a database?

我必須在我的存儲庫中執行 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();
}

其中 UserProjection 是我定義的投影:

public interface UserProjection {
    String getU_httpstatus();
    String getU_queryparam();
}

class userRequestResponse 的字段比 u_httpstatus 和 u_queryparam 多,但我的響應中只需要這兩個字段。

public @ResponseBody List<UserRequestResponse> getAllRequestResponseRecords() {
    return userRequestResponseRepository.findAll() ;
}

如何修改上述代碼 (findAll()) 以從我的自定義查詢中獲取結果,而不是從默認 CrudRepository findAll() (返回所有字段)中獲取結果。

首先,您不需要添加@Query來進行預測。 只需將UserProjection作為存儲庫中方法的返回類型就足夠了。 更多關於這里

其次,您可以在存儲庫中使用以下方法作為基於投影的 findAll 方法;

public List<UserProjection> findAllProjectedBy();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM