如何使用Java 8从对象列表中移除一个字段,以下是我想实现的示例。

huangapple go评论99阅读模式
英文:

How to remove a field from a List of Object using java 8, below is the example of what I want to achieve

问题

我有一个名为Category的实体类(示例如下)

  1. @Entity
  2. class Category {
  3. private int id;
  4. private String name;
  5. private String address;
  6. private Date createDate;
  7. private Date modifiedDate;
  8. }

我正在使用JPA,当我执行

  1. findAll(); // JPA repository

我也会获取createdDate和modifiedDate,但我不想获取它们。

那么有没有一种方法可以通过移除createDate和modifiedDate字段来筛选获取的列表?

英文:

I have an Entity class as Category (below is sample)

  1. @Entity
  2. class Category {
  3. private int id;
  4. private String name;
  5. private String address;
  6. private Date createDate;
  7. private Date modifiedDate;
  8. }

I am using JPA, and when I am doing

  1. findAll(); // JPA repository

I am getting createdDate and modifiedDate as well, But I don't want to fetch them.

So Is there a way to filter the fetched list by removing the createDate and modifiedDate fields. ?

答案1

得分: 1

  1. @Entity
  2. class Category {
  3. private int id;
  4. private String name;
  5. private String address;
  6. private Date createDate;
  7. private Date modifiedDate;
  8. Category(){
  9. }
  10. // This constructor will be used to fetch only desired columns
  11. Category(String id, String name, String address){
  12. this.id = id;
  13. this.name = name;
  14. this.address = address;
  15. }
  16. }

在你的 repository 中,你需要定义 @Query 如下:

  1. @Query("SELECT new com.test.Category(cat.id, cat.name, cat.address) FROM Category cat")
  2. List<Category> findAll();

注意: 你需要将 com.test.Category 替换为你实际的 Category 类所在的包路径。

英文:
  1. @Entity
  2. class Category {
  3. private int id;
  4. private String name;
  5. private String address;
  6. private Date createDate;
  7. private Date modifiedDate;
  8. Category(){
  9. }
  10. // This constructor will be used to fetch only desired columns
  11. Category(String id, String name, String address){
  12. this.id = id;
  13. this.name = name;
  14. this.address = address;
  15. }
  16. }

In your repository you need to define the @Query as

  1. @Query(&quot;SELECT new com.test.Category(cat.id, cat.name, cat.address) FROM Category cat&quot;)
  2. List&lt;Category&gt; findAll();

Note: You need to replace com.test.Category to your actual package for Category

huangapple
  • 本文由 发表于 2020年9月10日 05:24:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63819724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定