首页 > 解决方案 > Spring-如何从对象列表中删除属性?

问题描述

我有一个具有以下属性的实体“人”,

Id
Name
F-Name
Age
Address

当我在 Person 上调用存储库函数 findAll() 时,它会返回一个 Person 列表。

List<Person> list = somefuntionToConvertIterableToList(personRepository.findAll());

这个列表有多个 Person 类型的对象。

人...... Id1,Name1,F-Name1,Age1,Address1

人 .......IdN,NameN, F-NameN, AgeN, AddressN

我需要从所有 Persons 中删除“Id”,我该怎么办?

我知道我们可以使用“删除”来删除列表中的元素,但是如何删除元素中的属性呢?

标签: springspring-bootjpacollections

解决方案


您当然可以设置idnull 或在序列化中添加忽略,但也许您根本不想加载id。通常你会使用DTOorTuple来决定填充哪些字段。所以不要先填充所有然后删除不需要的(我没有使用你的Person但只是一个简化的示例类)。

存储库中的元组查询就像(JPQL):

@Query("SELECT te.name AS name, te.created as created FROM TestEntity te")
List<Tuple> findAllTuple();

这将需要做额外的工作以使元组在序列化时与原始实体相对应。所以最好用一个DTO,比如:

// This class would be exactly as your Person but without that id
@AllArgsConstructor // you need the constructor for new in jpql
public class TestEntityDto {
    private String name;
    private LocalDateTime created;
}

而您的存储库中的查询将类似于:

@Query("SELECT NEW org.example.data.entity.dto.TestEntityDto(te.name, te.created) FROM TestEntity te")
List<TestEntityDto> findAllDto();

推荐阅读