DTO到实体和实体到DTO

时间:2012-12-16 06:57:52

标签: hibernate domain-driven-design dozer

我们将使用DTO向表示层发送数据和从表示层发送数据。 我们有以下几层:

  • 门面
  • AppService服务

我们使用Dozer帮助我们将实体转换为dto。 但我现在有2个问题:

  1. 从实体到dto我们可以使用推土机,但是从dto到实体可以使用推土机吗?如果是,怎么做?
  2. 我在哪里创建实体?在门面或DTOAssembler?
  3. 例如,我必须注册一本书。实体看起来像:

    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;
    }
    

    一个更好吗?或者它可以以更好的方式实施..?

1 个答案:

答案 0 :(得分:7)

通常,您不会将对象(域实体的DTO表示)传输回服务器。因为如果你这样做,你就会打破封装,因为任何人都可以将更改应用到DTO,然后再发回信息。

相反,您应该创建一个用于修改对象的服务接口,因为它允许 服务器 对其模型应用更改。

因此,该服务实际上分为两部分:

  1. 用于获取所有实体的DTO表示的查询部分
  2. 用于对实体应用更改的命令部分
相关问题