gpt4 book ai didi

java - 将列表对象转换为列表objectDto java的最佳实践

转载 作者:行者123 更新时间:2023-12-01 17:44:47 26 4
gpt4 key购买 nike

我已经获取了所有数据并将其从 object 转换为 objectDto。但是,不知何故,我觉得我的代码还不好。在这里我需要您的帮助,我需要任何引用/建议来使我的代码更好(在性能方面)。这是我的工作代码:

    @Override
public List<BookDto> findAll() throws Exception {
try {
List<Book> list = bookDao.findAll();
List<BookDto> listDto = new ArrayList<>();

for (Book book : list) {
BookDto bookDto = new BookDto();
Set<AuthorDto> listAuthorDto = new HashSet<AuthorDto>();
Set<Author> dataAuthor = new HashSet<Author>();
book.getAuthor().iterator().forEachRemaining(dataAuthor::add);

BeanUtils.copyProperties(book, bookDto, "author", "category");
bookDto.setCategory(book.getCategory().getCategory());

for (Author author : dataAuthor) {
AuthorDto authorDto = new AuthorDto();
BeanUtils.copyProperties(author, authorDto);
listAuthorDto.add(authorDto);
}

bookDto.setAuthor(listAuthorDto);
listDto.add(bookDto);
}
return listDto;
} catch (Exception e) {
throw new Exception(e);
}
}

这是我需要的输出(已通过上面的代码实现):

[
{
"title": "book1",
"year": "2013",
"author": [
{
"name": "john",
"address": "NY"
},
{
"name": "angel",
"address": "LA"
}
],
"category": "science"
},
{
"title": "book2",
"year": "2014",
"author": [
{
"name": "john",
"address": "NY"
}
],
"category": "science"
},
{
"title": "book3",
"year": "2009",
"author": [
{
"name": "angel",
"address": "LA"
}
],
"category": "comedy"
}
]

最佳答案

与其重新发明轮子并自己编写它,不如使用现有的库/工具,这是为此而设计的。

我建议使用ModelMapper这是一个很棒的 DTO/实体映射库,您只需要一行即可将实体转换为 DTO,例如:

ModelMapper modelMapper = new ModelMapper();
BookDto bookDTO = modelMapper.map(book, BookDto.class);

您可以查看 library's Examples pageEntity To DTO Conversion for a Spring REST API tutorial更深入地了解这个库。

关于java - 将列表对象转换为列表objectDto java的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56846968/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com