【问题标题】:Change Spring findAll() return type更改 Spring findAll() 返回类型
【发布时间】:2019-07-03 23:19:36
【问题描述】:

我想运行 Spring JPA 的 findAll() 方法,但返回所有记录,然后不返回所有记录。我想从投影返回值。喜欢

public interface StudentRepository extends CrudRepository<Student, Integer>{
    //How can I achieve this
    List<NamesOnly> findAll(); 
   //Which returns list of only student names;
}

public interface NamesOnly{
@Value("#{target.firstName+ ' ' + target.lastName}")
    String getFullName();
}

或者,

how to convert List<Student> given by default findAll() to List<NamesOnly>??

【问题讨论】:

    标签: spring interface spring-data-jpa overriding spring-projections


    【解决方案1】:

    你可以做到。只在一个字段中创建 StudentD:studentName 并在 StudentRepository 中进行:

      List<StudentDto> findAllStudent(); 
    

    StudentDTO.class

    public class StudentDTO {
           private String studentName //this is field you want return
    
         }
    

    或者您可以使用注释@JsonIgnore 在您不想在响应查看行时显示的字段上方:

      **Student.class**
    
    
      @JsonIgnore
      private String firstName //this is field you don't want spring reponse.
    

    【讨论】:

      【解决方案2】:

      您将不得不在另一种方法中执行更改,您无法更改由您定义的存储库返回类型:extends CrudRepository&lt;Student, Integer&gt;

      【讨论】:

      • 不,我正在考虑从默认 List 返回 List 或者如果这不可能,如何转换 List Class Types!
      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 2022-09-30
      • 2014-11-15
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 2017-03-13
      相关资源
      最近更新 更多