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

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

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

问题

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

@Entity
class Category {
private int id;
private String name;
private String address;
private Date createDate;
private Date modifiedDate;
}

我正在使用JPA,当我执行

findAll(); // JPA repository

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

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

英文:

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

@Entity
class Category {
private int id;
private String name;
private String address;
private Date createDate;
private Date modifiedDate;
}

I am using JPA, and when I am doing

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

@Entity
class Category {
   private int id;
   private String name;
   private String address;
   private Date createDate;
   private Date modifiedDate;

   Category(){
   }

   // This constructor will be used to fetch only desired columns
   Category(String id, String name, String address){
        this.id =  id;
        this.name = name;
        this.address = address;
   }
}

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

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

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

英文:
@Entity
class Category {
   private int id;
   private String name;
   private String address;
   private Date createDate;
   private Date modifiedDate;

   Category(){
   }

   // This constructor will be used to fetch only desired columns
   Category(String id, String name, String address){
        this.id =  id;
        this.name = name;
        this.address = address;
   }
}

In your repository you need to define the @Query as

@Query(&quot;SELECT new com.test.Category(cat.id, cat.name, cat.address) FROM Category cat&quot;)
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:

确定