spring - 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”,我该怎么办?
我知道我们可以使用“删除”来删除列表中的元素,但是如何删除元素中的属性呢?
解决方案
您当然可以设置id
null 或在序列化中添加忽略,但也许您根本不想加载id
。通常你会使用DTO
orTuple
来决定填充哪些字段。所以不要先填充所有然后删除不需要的(我没有使用你的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();
推荐阅读
- ruby-on-rails - 在 Rails 中的 has_many 关系中排序引用
- c - 如何从索引a到索引b获取数组的最大元素?
- ios - Apollo Client 生成一个空的 API.swift 文件
- python - 在 Python 中保存自定义类实例的状态更改
- visual-studio-code - Visual Studio 语言扩展,如何调用自己的函数?
- node.js - 错误:将用户名和密码添加到 mongodb 连接字符串后,UTF8 不是函数
- c# - 没有应用程序与 C# 中此操作异常的指定文件关联
- laravel - Laravel“拒绝访问服务器上的此资源!” cpanel中的错误
- datetime - 更改 SQL Server 表中现有列数据时间中的日期时间列
- python - 如何使用python对没有标题的csv文件进行排序?