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

Best practice to convert list object to list objectDto java

我已经获取了所有数据并将对象转换为 objectDto。但是,不知何故,我觉得我的代码还不够好。在这里我需要你的帮助,我需要任何 reference/advice 来使我的代码更好(性能)。这是我的工作代码:

    @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"
    }
]

你最好使用现有的 library/tool 而不是 re-inventing 轮子并自己编写它。

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

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

您可以查看 library's Examples page or the Entity To DTO Conversion for a Spring REST API tutorial 以更深入地了解此库。

首先,这段代码:

} catch (Exception e) {
   throw new Exception(e);
}

太荒谬了,我建议不要向任何人展示此代码。

第二 -

List<Book> list = bookDao.findAll();
List<BookDto> listDto = new ArrayList<>(); 

您可以在此处分配精确大小的 listDto,因为您 list.size() == listDto.size(),并且在您知道确切大小或目标集合的所有其他地方,您可能有使用它。 (对于哈希集也要注意负载因子)。

BeanUtils.copyProperties(

这里使用了不必要的反射,直接调用方法会提高性能。

如果您想要更多 - 您可以考虑使用 Hash-sets 来寻找独特的作者,可能有更有效的方法来做到这一点。

作为一般性建议,您可能希望使用 http://mapstruct.org/documentation/stable/reference/html/ 将实体映射到 dto 以避免编写样板代码。

所有这些问题看起来都像是代码审查的任务。不是吗?