我们将使用DTO向表示层发送数据和从表示层发送数据。 我们有以下几层:
我们使用Dozer帮助我们将实体转换为dto。 但我现在有2个问题:
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;
}
一个更好吗?或者它可以以更好的方式实施..?
答案 0 :(得分:7)
通常,您不会将对象(域实体的DTO表示)传输回服务器。因为如果你这样做,你就会打破封装,因为任何人都可以将更改应用到DTO,然后再发回信息。
相反,您应该创建一个用于修改对象的服务接口,因为它允许 服务器 对其模型应用更改。
因此,该服务实际上分为两部分: