英文:
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("SELECT new com.test.Category(cat.id, cat.name, cat.address) FROM Category cat")
List<Category> findAll();
Note: You need to replace com.test.Category
to your actual package for Category
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论