我们将使用 DTO 向表示层发送数据和从表示层发送数据。我们有如下层:
- 正面
- 应用服务
- 领域
我们已经使用 Dozer 帮助我们将实体转换为 dto。但我现在有 2 个问题:
- 从实体到 dto 我们可以使用推土机,但是从 dto 到实体我们可以使用推土机吗?如果是,如何?
- 我应该在哪里创建实体?在门面或 DTOAssembler 中?
例如,我必须注册一本书。这本书实体看起来像:
Book{
public Book(BookNumber number,String name){
//make sure every book has a business number,
//and the number can't change once the book is created.
this.bookNumber = number;
..
}
}
我们有一个 DTOAssembler:
BookDTOAssembler{
BookDTO toDAO(bookEntity){
...
}
BookEntiy fromDTO(book DTO,BookRepository bookRepository){
//1.Where should i create book entity?
//2.Is there any effective way to convert dto to entity in java world?
}
}
选项1
the BookManagedFacade has a registerBook function:
public registerBook(bookDTO){
Book book = BookDTOAssembler.fromDTO(book DTO);
}
//Create book in BookDTOAssembler.fromDTO
public static BookEntiy fromDTO(BookDTO bookDTO,BookRepository bookRepository){
//book is never registered
if (0==bookDTO.getBookID()){
Book book = new Book(bookRepository.generateNextBookNumber(),bookDTO.getName());
}else{
//book is been registed so we get it from Repository
book = bookRepository.findById(bookDTO.getBookID());
}
book.setAuthor(bookDTO.getAuthor);
...
return book;
}
选项 2
the BookManagedFacade has a registerBook function:
public registerBook(bookDTO){
Book book = new Book(bookRepository.generateNextBookNumber(),bookDTO.getName());
book = BookDTOAssembler.fromDTO(book DTO,book);
}
//add another function in BookDTOAssembler.fromDTO
public static BookEntiy fromDTO(BookDTO bookDTO,Book book){
book.setAuthor(bookDTO.getAuthor);
...
return book;
}
带一个更好?或者它可以以更好的方式实施..?