【发布时间】:2019-07-02 06:59:26
【问题描述】:
我已经完成了获取所有数据并从 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"
}
]
【问题讨论】:
-
可能使用一些现有的库,例如“Gson”,将完全消除您自定义代码中的任何需求。
-
您可以使用模型映射器之类的库。
标签: java spring spring-boot entity dto