为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用弹簧数据从弹簧启动中的实体中选择几个字段?

如何使用弹簧数据从弹簧启动中的实体中选择几个字段?

繁花不似锦 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 关注
  • 118 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号