我们将使用DTO向表示层发送数据和从表示层发送数据。我们有以下几层:
我们使用Dozer来帮助我们将实体转换为dto。但我现在有两个问题:
例如,我必须注册一本书。这本书的实体看起来就像:
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;
}用一个更好?或者可以用一种更好的方式实现?
发布于 2012-12-18 13:45:05
通常,您不会将对象(域实体的DTO表示)传输回服务器。因为如果这样做,就会破坏封装,因为任何人都可以将更改应用于do,然后将信息发回。
相反,您应该创建一个服务接口,用于修改对象,因为它允许服务器对其模型进行更改。
因此,这项服务实际上分为两部分:
https://stackoverflow.com/questions/13899291
复制相似问题