Pojo到DTO-Bean映射

时间:2018-07-13 18:51:08

标签: java javabeans mapper

我经历了stackoverflows,ModelMapper,Dozer等。 我不知道将实体映射到DTO的现有逻辑。

以下是实体和DTO的类:

package com.entity;

public class EmployeeRequest {

    private User user;
    private String userId;

    public EmployeeRequest(){
    }   
    //Getters and Setters Below
}

package com.entity;

public class User {

    private Address address;
    private Name name;

    public User(){
    }
    //Getters and Setters Below
}

package com.entity;

public class Address {

    private int flatNo; 
    private String city;

    public Address(){
    }
    //Getters and Setters Below
}

package com.entity;

public class Name {

    private String firstName;
    private String lastName;

    public Name(){
    }   
    //Getters and Setters Below
}

package com.dto;

public class EmployeeRequestDTO {

    private UserDTO user;
    private String userId;

    public EmployeeRequestDTO(){
    }
    //Getters and Setters Below
}

package com.dto;

public class UserDTO {

    private AddressDTO address;
    private NameDTO name;

    public UserDTO() {
    }
    //Getters and Setters Below
}

package com.dto;

public class AddressDTO {

    private int flatNo;
    private String city;

    public AddressDTO() {
    }
    //Getters and Setters Below
}

package com.dto;

public class NameDTO {

    private String firstName;
    private String lastName;

    public NameDTO(){       
    }
    //Getters and Setters Below
}

//映射类:

package com.service;

import com.dto.EmployeeRequestDTO;
import com.entity.Address;
import com.entity.EmployeeRequest;
import com.entity.Name;
import com.entity.User;

public class EntityModelMapperService {

    public static void main(String[] args) {

        Address address=new Address();
        address.setFlatNo(72);
        address.setCity("Kayalpatnam");

        Name name=new Name();
        name.setFirstName("Abdul");
        name.setLastName("Basith");

        User user = new User();
        user.setAddress(address);
        user.setName(name);

        EmployeeRequest employeeRequest = new EmployeeRequest();
        employeeRequest.setUser(user);      
    }
}

如何将实体值映射到DTO?分配后,实体中的任何更改都不应影响DTO,反之亦然。

2 个答案:

答案 0 :(得分:1)

下面1行足以映射:

EmployeeRequestDTO employeeRequestDTO = new ModelMapper().map(employeeRequest, EmployeeRequestDTO.class);

答案 1 :(得分:0)

我建议为此查看ModelProjector。它以很小的占用空间和额外的编码完全支持您所设想的用例。