亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用彈簧數據從彈簧啟動中的實體中選擇幾個字段?

如何使用彈簧數據從彈簧啟動中的實體中選擇幾個字段?

繁花不似錦 2022-09-14 15:17:41
我有一個用例,我想顯示實體的內容,但隱藏某些字段。我的實體如下 -實體public class StudentDetail {@Idprivate Long ID;private String firstName;private String middleName;private String lastName;@JsonFormat(pattern="dd-MMM-yyyy", timezone="IST")@Temporal(TemporalType.DATE)private Date dateOfBirth;}它還具有許多其他屬性,我在這里不顯示。存儲庫 -@Repositorypublic interface StudentDetailsRepository extends JpaRepository<StudentDetail, Integer> {@Query("select d from StudentDetail d where month(d.dateOfBirth) = ?1 ")    List<StudentDetail> getStudentListBasedOnDateOfBirth(int month);}服務等級 -public List<StudentDetail> getStudentBirthdayDetails(int month) {        List<StudentDetail> StudentDetail = StudentDetailsRepository.getStudentListBasedOnDateOfBirth(month);        return StudentDetail;    }還有一個控制器類,它使用參數調用 Service 類來過濾數據集。month我想做的是修改存儲庫類中的查詢,并僅包含 、 和 屬性。存儲庫類應隱藏該字段。我意識到以下查詢將返回過濾后的項目 -firstnamemiddleNamelastNamedateOfBirthselect d.firstName, d.middleName, d.lastName from StudentDetail d where month(d.dateOfBirth) = ?1 但是,該類的返回類型是 實體類型 學生詳細信息 。僅從中選擇幾個字段將導致錯誤。所以,我想知道我應該在/ 和類中進行哪些更改(假設只有返回類的類型會更改)?Repositoryreposervicecontroller
查看完整描述

1 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

這被稱為投影,Spring為您提供了兩種實現它的方法。

請記住,這在JPA術語中存在,而不僅僅是在春季。


以您的為出發點Repository


@Repository

public interface StudentDetailsRepository extends JpaRepository<StudentDetail, Integer> {

   ...

}

我們可以使用


interface-基于投影

只需創建一個界面,表示您想要的結果

public interface StudentDetailProjection {

   String getFirstName();

   String getMiddleName();

   String getLastName();

}

并將方法添加到您的Repository


@Repository

public interface StudentDetailsRepository extends JpaRepository<StudentDetail, Integer> {

   StudentDetailProjection get...(...);

}

Spring將自動子類化該接口,它將要求JPA執行一個查詢,該查詢將僅提取指定的字段。


class基于-基于的投影

的工作方式幾乎與基于接口的投影相同,但不需要代理和子類,因為您正在為Spring提供一個具體的類。

public class StudentDetailProjection {

   private final String getFirstName;

   private final String getMiddleName;

   private final String getLastName;


   public StudentDetailProjection(

      final String getFirstName,

      final String getMiddleName,

      final String getLastName,

   ) {...}


   // Getters

}

文檔更深入。


另外,必讀的是JPA大師弗拉德·米哈爾塞亞的這篇博客文章。


該方法可能看起來大致類似于


@Query("select new your.package.StudentDetailProjection(d.firstName, d.middleName, d.lastName) from StudentDetail d where month(d.dateOfBirth) = ?1")

List<StudentDetailProjection> getStudentListBasedOnDateOfBirth(final int month);

這將遵循具體選項 (2),因為需要構造函數。class


查看完整回答
反對 回復 2022-09-14
  • 1 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號