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

我有一个用例,我想显示实体的内容,但隐藏某些字段。我的实体如下 -


实体


public class StudentDetail {


@Id

private Long ID;

private String firstName;

private String middleName;

private String lastName;


@JsonFormat(pattern="dd-MMM-yyyy", timezone="IST")

@Temporal(TemporalType.DATE)

private Date dateOfBirth;

}

它还具有许多其他属性,我在这里不显示。


存储库 -


@Repository

public 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


我想做的是修改存储库类中的查询,并仅包含 、 和 属性。存储库类应隐藏该字段。我意识到以下查询将返回过滤后的项目 -firstnamemiddleNamelastNamedateOfBirth


select d.firstName, d.middleName, d.lastName from StudentDetail d where month(d.dateOfBirth) = ?1 

但是,该类的返回类型是 实体类型 学生详细信息 。仅从中选择几个字段将导致错误。所以,我想知道我应该在/ 和类中进行哪些更改(假设只有返回类的类型会更改)?Repositoryreposervicecontroller


繁花不似锦
浏览 119回答 1
1回答

九州编程

这被称为投影,Spring为您提供了两种实现它的方法。请记住,这在JPA术语中存在,而不仅仅是在春季。以您的为出发点Repository@Repositorypublic interface StudentDetailsRepository extends JpaRepository<StudentDetail, Integer> {&nbsp; &nbsp;...}我们可以使用interface-基于投影只需创建一个界面,表示您想要的结果public interface StudentDetailProjection {&nbsp; &nbsp;String getFirstName();&nbsp; &nbsp;String getMiddleName();&nbsp; &nbsp;String getLastName();}并将方法添加到您的Repository@Repositorypublic interface StudentDetailsRepository extends JpaRepository<StudentDetail, Integer> {&nbsp; &nbsp;StudentDetailProjection get...(...);}Spring将自动子类化该接口,它将要求JPA执行一个查询,该查询将仅提取指定的字段。class基于-基于的投影的工作方式几乎与基于接口的投影相同,但不需要代理和子类,因为您正在为Spring提供一个具体的类。public class StudentDetailProjection {&nbsp; &nbsp;private final String getFirstName;&nbsp; &nbsp;private final String getMiddleName;&nbsp; &nbsp;private final String getLastName;&nbsp; &nbsp;public StudentDetailProjection(&nbsp; &nbsp; &nbsp; final String getFirstName,&nbsp; &nbsp; &nbsp; final String getMiddleName,&nbsp; &nbsp; &nbsp; final String getLastName,&nbsp; &nbsp;) {...}&nbsp; &nbsp;// 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java