我们将使用DTO在表示层之间来回发送数据。我们有像这样的图层:
并且我们使用推土机来帮助我们将实体转换为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; }
用一个更好?或者它可以以更好的方式实现..?
通常,您不将对象(域实体的DTO表示形式)传输回服务器。因为这样做会破坏封装,因为任何人都可以将更改应用于DTO,然后将信息发送回去。
相反,您应该创建一个用于修改对象的服务接口,因为它允许 服务器 将更改应用于其模型。
因此,服务实际上分为两部分: