tob*_*ato 5 domain-driven-design hibernate dozer
我们将使用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;
..
}
}
Run Code Online (Sandbox Code Playgroud)
我们有一个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?
}
}
Run Code Online (Sandbox Code Playgroud)
选项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;
}
Run Code Online (Sandbox Code Playgroud)
选项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;
}
Run Code Online (Sandbox Code Playgroud)
一个更好吗?或者它可以以更好的方式实施..?
通常,您不会将对象(域实体的DTO表示)传输回服务器.因为如果你这样做,你就会打破封装,因为任何人都可以将更改应用到DTO,然后再发回信息.
相反,您应该创建一个用于修改对象的服务接口,因为它允许服务器将更改应用于它的模型.
因此,该服务实际上分为两部分:
| 归档时间: |
|
| 查看次数: |
12273 次 |
| 最近记录: |