MapStruct入门及集成springboot

MapStruct入门及集成springboot

MapStruct官网地址: http://mapstruct.org/

1、引入依赖

maven的pom.xml

...
<properties>
    <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
</properties>
...
<dependencies>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</version>
    </dependency>
</dependencies>
...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source> <!-- depending on your project -->
                <target>1.8</target> <!-- depending on your project -->
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${org.mapstruct.version}</version>
                    </path>
                    <!-- other annotation processors -->
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>


    1.4.2.Final



    org.mapstruct
    mapstruct
    ${org.mapstruct.version}



    org.mapstruct
    mapstruct-processor
    ${org.mapstruct.version}

2、简单示例

2.1 新增实体

admin 实体:

public class Admin {

    private String name;

    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

user实体:

public class User {

    private String name;

    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

2.2 定义mapper

mapper:

import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

@Mapper
public interface UserMapper {

    UserMapper INSTANCE  = Mappers.getMapper(UserMapper.class);

    Admin userToAdmin(User user);
}

2.3 测试效果

测试demo:

public static void main(String[] args) {
        User user = new User();
        user.setAddress("213");
        user.setName("张三");
        Admin admin = UserMapper.INSTANCE.userToAdmin(user);
        System.out.println(admin.getAddress());
        System.out.println(admin.getName());
    }

结果:

213
张三

3、多个入参构造一个对象

3.1 新增实体

Role:

public class Role {

    private String name;

    private String roleId;

    private String description;

    public Role() {
    }

    public Role(String name, String roleId, String description) {
        this.name = name;
        this.roleId = roleId;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

User:

public class User {

    private Long userId;

    private String name;

    private String address;

    public User() {
    }

    public User(Long userId, String name, String address) {
        this.userId = userId;
        this.name = name;
        this.address = address;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

UserRoleDTO:

public class UserRoleDTO {

    private Long id;

    private String name;

    private String address;

    private String roleName;

    private String roleId;

    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "UserRoleDTO{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", roleName='" + roleName + '\'' +
                ", roleId='" + roleId + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

3.2 定义mapper

mapper:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

@Mapper
public interface UserMapper {

    UserMapper INSTANCE  = Mappers.getMapper(UserMapper.class);

    @Mappings({
            //user中的userId绑定到目标对象的id属性中
            @Mapping(source = "user.userId", target = "id"),
            //user和 role中都有name属性,所以需要指定一个来传给UserRoleDto
            @Mapping(source = "user.name",target = "name")

    })
    UserRoleDTO toUserRoleDTO(User user, Role role);
}

3.3 测试效果

测试demo:

public static void main(String[] args) {
        User user = new User(1L, "小王八蛋", "北京");
        Role role = new Role("管理员", "2", "描述");
        UserRoleDTO userRoleDTO = UserMapper.INSTANCE.toUserRoleDTO(user, role);
        System.out.println(userRoleDTO.toString());
    }

结果:

UserRoleDTO{id=1, name='小王八蛋', address='北京', roleName='null', roleId='2', description='描述'}

4、数据类型转换 (int -> string 等)

4.1 新增实体

product:

import java.util.Date;

public class Product {

    private int price;

    private int stock;

    private Date saleTime;

    private Date validTime;

    public Product() {
    }

    public Product(int price, int stock, Date saleTime, Date validTime) {
        this.price = price;
        this.stock = stock;
        this.saleTime = saleTime;
        this.validTime = validTime;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public Date getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(Date saleTime) {
        this.saleTime = saleTime;
    }

    public Date getValidTime() {
        return validTime;
    }

    public void setValidTime(Date validTime) {
        this.validTime = validTime;
    }
}

productDTO:

public class ProductDTO {

    private String price;

    private String stock;

    private String saleTime;

    private String  validTime;

    @Override
    public String toString() {
        return "ProductDTO{" +
                "price='" + price + '\'' +
                ", stock='" + stock + '\'' +
                ", saleTime='" + saleTime + '\'' +
                ", validTime='" + validTime + '\'' +
                '}';
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getStock() {
        return stock;
    }

    public void setStock(String stock) {
        this.stock = stock;
    }

    public String getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(String saleTime) {
        this.saleTime = saleTime;
    }

    public String getValidTime() {
        return validTime;
    }

    public void setValidTime(String validTime) {
        this.validTime = validTime;
    }
}

4.2 定义mapper

mapper:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

@Mapper
public interface ProductMapper {

    ProductMapper INSTANCE = Mappers.getMapper(ProductMapper.class);

    /**
     * numberFormat 指定基本数据类型与String之间的转换
     * dateFormat 指定Date和String之间的转换
     */
    @Mappings({
            // 这里 # 表示多个数字,  0 表示一个数字(0-9)
            @Mapping(source = "price", target = "price", numberFormat = "#.00元"),
            @Mapping(source = "stock", target = "stock", numberFormat = "#个"),
            @Mapping(target = "saleTime", dateFormat = "yyyy-MM-dd HH:mm:ss"),
            @Mapping(target = "validTime", dateFormat = "yyyy-MM-dd HH:mm")
    })
    ProductDTO toDto(Product product);;
}

4.3 测试效果

测试demo:

 public static void main(String[] args) {
        Product product = new Product(1,1,new Date(),new Date());
        ProductDTO productDTO = ProductMapper.INSTANCE.toDto(product);
        System.out.println(productDTO.toString());
    }

结果:

ProductDTO{price='1.00元', stock='1个', saleTime='2022-02-28 17:39:29', validTime='2022-02-28 17:39'}

5、包含其他类的映射

5.1 相同类

5.1.1 新增实体

user:

public class User {

    private Long userId;

    private String name;

    private String address;

    private Role role;

    public User() {
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public User(Long userId, String name, String address) {
        this.userId = userId;
        this.name = name;
        this.address = address;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


role:

public class Role {

    private String name;

    private String roleId;

    private String description;

    public Role() {
    }

    public Role(String name, String roleId, String description) {
        this.name = name;
        this.roleId = roleId;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Role{" +
                "name='" + name + '\'' +
                ", roleId='" + roleId + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}


UserRoleDTO:

public class UserRoleDTO {

    private Long id;

    private String name;

    private String address;

    private String roleName;

    private String roleId;

    private String description;

    private Role role;

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "UserRoleDTO{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", roleName='" + roleName + '\'' +
                ", roleId='" + roleId + '\'' +
                ", description='" + description + '\'' +
                ", role=" + role +
                '}';
    }
}


5.1.2 定义mapper

mapper:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

@Mapper
public interface UserMapper {

    UserMapper INSTANCE  = Mappers.getMapper(UserMapper.class);


    // role 的属性名一样,类型也一样,不用写Mapping,还有就是 role的赋值是浅拷贝 只拷贝引用,不生成新的对象
    @Mapping(source = "userId", target = "id")// 把user中的userId绑定到目标对象的id属性中
    UserRoleDTO toUserRoleDto(User user);

}

5.1.3 测试效果

测试demo:

 public static void main(String[] args) {
        User user = new User(1L, "小王八蛋", "北京");
        Role role = new Role("管理员", "2", "描述");
        user.setRole(role);
        UserRoleDTO userRoleDTO = UserMapper.INSTANCE.toUserRoleDto(user);
        System.out.println(userRoleDTO.toString());
    }

结果:

UserRoleDTO{id=1, name='小王八蛋', address='北京', roleName='null', roleId='null', description='null', role=Role{name='管理员', roleId='2', description='描述'}}

5.2 不同类

5.2.1 新增实体

user:

public class User {

    private Long userId;

    private String name;

    private String address;

    private Role role;

    public User() {
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public User(Long userId, String name, String address) {
        this.userId = userId;
        this.name = name;
        this.address = address;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


role:

public class Role {

    private String name;

    private String roleId;

    private String description;

    public Role() {
    }

    public Role(String name, String roleId, String description) {
        this.name = name;
        this.roleId = roleId;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Role{" +
                "name='" + name + '\'' +
                ", roleId='" + roleId + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}


UserRoleDTO:

public class UserRoleDTO {

    private Long id;

    private String name;

    private String address;

    private String roleName;

    private String roleId;

    private String description;

    private RoleDTO role;

    public RoleDTO getRole() {
        return role;
    }

    public void setRole(RoleDTO role) {
        this.role = role;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "UserRoleDTO{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", roleName='" + roleName + '\'' +
                ", roleId='" + roleId + '\'' +
                ", description='" + description + '\'' +
                ", role=" + role +
                '}';
    }
}


RoleDTO:

public class RoleDTO {

    private String name;

    private String id;

    private String description;


    public RoleDTO(String name, String id, String description) {
        this.name = name;
        this.id = id;
        this.description = description;
    }

    public RoleDTO() {
    }

    @Override
    public String toString() {
        return "RoleDTO{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}


5.2.2 定义mapper

mapper:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

@Mapper
public interface UserMapper {

    UserMapper INSTANCE  = Mappers.getMapper(UserMapper.class);

    // 这两个方法写在一起也行,分别写在两个接口里也行,执行时,都会自动调用
    @Mapping(source = "userId", target = "id") // 把user中的userId绑定到目标对象的id属性中
    UserRoleDTO toUserRoleDto(User user);

    // 当上面那个toUserRoleDto方法调用时,会自动调用这个方法来完成 User类中的Role 到 UserRoleDTO类中的RoleDTO  的转换
    @Mapping(source = "roleId", target = "id")
    RoleDTO toRoleDto(Role role);


}

5.2.3 测试效果

测试demo:

 public static void main(String[] args) {
        Product product = new Product(1,1,new Date(),new Date());
        ProductDTO productDTO = ProductMapper.INSTANCE.toDto(product);
        System.out.println(productDTO.toString());
    }

结果:

UserRoleDTO{id=1, name='小王八蛋', address='北京', roleName='null', roleId='null', description='null', role=RoleDTO{name='管理员', id='2', description='描述'}}

6、自定义映射方式

6.1 新增实体

product:

import java.util.Date;

public class Product {

    private int price;

    private int stock;

    private Date saleTime;

    private Date validTime;

    private Boolean isDone;

    public Product() {
    }

    public Product(int price, int stock, Date saleTime, Date validTime, Boolean isDone) {
        this.price = price;
        this.stock = stock;
        this.saleTime = saleTime;
        this.validTime = validTime;
        this.isDone = isDone;
    }

    public Boolean getIsDone() {
        return isDone;
    }

    public void setIsDone(Boolean done) {
        isDone = done;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public Date getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(Date saleTime) {
        this.saleTime = saleTime;
    }

    public Date getValidTime() {
        return validTime;
    }

    public void setValidTime(Date validTime) {
        this.validTime = validTime;
    }
}


productDTO:

public class ProductDTO {

    private String price;

    private String stock;

    private String saleTime;

    private String validTime;

    private String isDone;

    @Override
    public String toString() {
        return "ProductDTO{" +
                "price='" + price + '\'' +
                ", stock='" + stock + '\'' +
                ", saleTime='" + saleTime + '\'' +
                ", validTime='" + validTime + '\'' +
                ", isDone='" + isDone + '\'' +
                '}';
    }

    public String getIsDone() {
        return isDone;
    }

    public void setIsDone(String isDone) {
        this.isDone = isDone;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getStock() {
        return stock;
    }

    public void setStock(String stock) {
        this.stock = stock;
    }

    public String getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(String saleTime) {
        this.saleTime = saleTime;
    }

    public String getValidTime() {
        return validTime;
    }

    public void setValidTime(String validTime) {
        this.validTime = validTime;
    }
}

6.2 自定义映射

自定义:

import org.mapstruct.Named;

@Named("DoneFormater")
public class DoneFormater {

    @Named("DoneFormater")
    public String toStr(Boolean isDone) {
        if (isDone) {
            return "已完成";
        } else {
            return "未完成";
        }
    }

    @Named("DoneDetailFormater")
    public String toDetail(Boolean isDone) {
        if (isDone) {
            return "该产品已完成";
        } else {
            return "该产品未完成";
        }
    }

    public Boolean toBoolean(String str) {
        if (str.equals("已完成")) {
            return true;
        } else {
            return false;
        }
    }

}

6.3 定义mapper

mapper:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

// 通过uses 来导入上面我们写的 自定义映射方法
@Mapper( uses = {DoneFormater.class})
public interface ProductMapper {

    ProductMapper INSTANCE = Mappers.getMapper(ProductMapper.class);

    /**
     * numberFormat 指定基本数据类型与String之间的转换
     * dateFormat 指定Date和String之间的转换
     */
    @Mappings({
            // 这里 # 表示多个数字,  0 表示一个数字(0-9)
            @Mapping(source = "price", target = "price", numberFormat = "#.00元"),
            @Mapping(source = "stock", target = "stock", numberFormat = "#个"),
            @Mapping(target = "saleTime", dateFormat = "yyyy-MM-dd HH:mm:ss"),
            @Mapping(target = "validTime", dateFormat = "yyyy-MM-dd HH:mm"),
            // 当有多个方法 拥有一样的参数和返回类型时,需要指定使用其中的哪一个,使用qualifiedByName指定
            @Mapping(source = "isDone", target = "isDone", qualifiedByName = "DoneDetailFormater")
    })
    ProductDTO toDto(Product product);;
}

6.4 测试效果

测试demo:

public static void main(String[] args) {
        Product product = new Product(1,1,new Date(),new Date(),true);
        ProductDTO productDTO = ProductMapper.INSTANCE.toDto(product);
        System.out.println(productDTO.toString());
    }

效果:

ProductDTO{price='1.00元', stock='1个', saleTime='2022-02-28 22:18:25', validTime='2022-02-28 22:18', isDone='该产品已完成'}

7、 List映射

7.1 新增实体

product:

import java.util.Date;

public class Product {

    private int price;

    private int stock;

    private Date saleTime;

    private Date validTime;

    private Boolean isDone;

    public Product() {
    }

    public Product(int price, int stock, Date saleTime, Date validTime, Boolean isDone) {
        this.price = price;
        this.stock = stock;
        this.saleTime = saleTime;
        this.validTime = validTime;
        this.isDone = isDone;
    }

    public Boolean getIsDone() {
        return isDone;
    }

    public void setIsDone(Boolean done) {
        isDone = done;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public Date getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(Date saleTime) {
        this.saleTime = saleTime;
    }

    public Date getValidTime() {
        return validTime;
    }

    public void setValidTime(Date validTime) {
        this.validTime = validTime;
    }
}


productDTO:

public class ProductDTO {

    private String price;

    private String stock;

    private String saleTime;

    private String validTime;

    private String isDone;

    @Override
    public String toString() {
        return "ProductDTO{" +
                "price='" + price + '\'' +
                ", stock='" + stock + '\'' +
                ", saleTime='" + saleTime + '\'' +
                ", validTime='" + validTime + '\'' +
                ", isDone='" + isDone + '\'' +
                '}';
    }

    public String getIsDone() {
        return isDone;
    }

    public void setIsDone(String isDone) {
        this.isDone = isDone;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getStock() {
        return stock;
    }

    public void setStock(String stock) {
        this.stock = stock;
    }

    public String getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(String saleTime) {
        this.saleTime = saleTime;
    }

    public String getValidTime() {
        return validTime;
    }

    public void setValidTime(String validTime) {
        this.validTime = validTime;
    }
}

7.2 定义mapper

mapper:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

import java.util.List;

// 通过uses 来导入上面我们写的 自定义映射方法
@Mapper( uses = {DoneFormater.class})
public interface ProductMapper {

    ProductMapper INSTANCE = Mappers.getMapper(ProductMapper.class);

    /**
     * numberFormat 指定基本数据类型与String之间的转换
     * dateFormat 指定Date和String之间的转换
     */
    @Mappings({
            // 这里 # 表示多个数字,  0 表示一个数字(0-9)
            @Mapping(source = "price", target = "price", numberFormat = "#.00元"),
            @Mapping(source = "stock", target = "stock", numberFormat = "#个"),
            @Mapping(target = "saleTime", dateFormat = "yyyy-MM-dd HH:mm:ss"),
            @Mapping(target = "validTime", dateFormat = "yyyy-MM-dd HH:mm"),
            // 当有多个方法 拥有一样的参数和返回类型时,需要指定使用其中的哪一个,使用qualifiedByName指定
            @Mapping(source = "isDone", target = "isDone", qualifiedByName = "DoneDetailFormater")
    })
    ProductDTO toDto(Product product);

    // 	当执行 下面这个List的转换时,会遍历list: product,
    //  然后自动调用上面的Product转ProductDTO的转换方法,来进行转换
    List<ProductDTO> toList(List<Product> productList);
}

7.3 测试效果

测试demo:

public static void main(String[] args) {
        Product product = new Product(1,1,new Date(),new Date(),true);
        List<Product> list = new ArrayList<>();
        list.add(product);
        List<ProductDTO> productDTOS = ProductMapper.INSTANCE.toList(list);
        productDTOS.stream().forEach(productDTO -> System.out.println(productDTO.toString()));
    }

结果:

ProductDTO{price='1.00元', stock='1个', saleTime='2022-02-28 22:29:42', validTime='2022-02-28 22:29', isDone='该产品已完成'}

8、Map映射

8.1 定义mapper

import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.Date;
import java.util.Map;

@Mapper
public interface MapMapper {

    MapMapper INSTANCE = Mappers.getMapper(MapMapper.class);

    @MapMapping(valueDateFormat = "yyyy-MM-dd HH:mm:ss")
    Map<String, String> toDTO(Map<Long, Date> map);

}

8.2 测试效果

测试demo:

public static void main(String[] args) {
        Map<Long,Date> param = new HashMap<>();
        param.put(1L,new Date());
        Map<String, String> stringStringMap = MapMapper.INSTANCE.toDTO(param);
        for (Map.Entry<String, String> stringStringEntry : stringStringMap.entrySet()) {
            System.out.println(stringStringEntry.getKey());
            System.out.println(stringStringEntry.getValue());
        }
    }

结果:

1
2022-02-28 22:39:07

9、枚举映射

9.1 新增枚举

9.2 定义mapper

9.3 测试效果

10、使用表达式和默认值

10.1 定义mapper

// 通过uses 来导入上面我们写的 自定义映射方法
@Mapper( uses = {DoneFormater.class})
public interface ProductMapper {

    ProductMapper INSTANCE = Mappers.getMapper(ProductMapper.class);



        //expression中可以直接写Java代码
        @Mappings({
        // 设置默认值
        @Mapping(target = "productId", source = "productId", defaultValue = "123"), //当product的productId为null,设置为0
        // 表达式
        @Mapping(target = "price", expression = "java(product.getPrice1() + product.getPrice2())"),//直接相加
        @Mapping(target = "price2", expression = "java(MathUtils.addAndReturn0(product.getPrice1(), product.getPrice2()))"),//使用工具类处理
        // 常量
        @Mapping(target = "stock", constant = "100"), //固定设置为100, 常量
        })
        ProductDTO toDTO(Product product);
}

11、典型例子:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class RespLoginDTO {

    private String id;
    private String username;
    private String cname;
    private String sex;
    private String mobile;
    private String email;
    private String token;
    private String description;
    private String roleName;
    private String roleId;
    private List menus;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MenusBean {
       
        private int id;
        private String title;
        private String icon;
        private List children;


        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        public static class ChildrenBean {
      
            private int id;
            private String title;
            private String path;


        }
    }
}



@Mapper(componentModel = "spring")
public interface RespLoginDtoConverter {

    RespLoginDtoConverter INSTANCE = Mappers.getMapper(RespLoginDtoConverter.class);

    @Mappings({
            @Mapping(source = "user.userId", target = "id"),
            @Mapping(source = "userPerms", target = "menus")
    })
    RespLoginDTO createRespLoginDTO(User user, Role role, List userPerms, String token);


    // 下面的几个方法都是为了辅组完成上面的那个createRespLoginDTO转换而写的
    List createMenusBeans(List userPerms);

    @Mappings({
            @Mapping(source = "mainPerm.permId", target = "id"),
            @Mapping(source = "mainPerm.permTitle", target = "title"),
            @Mapping(source = "mainPerm.permIcon", target = "icon"),
            @Mapping(source = "childrenPrem", target = "children")
            //@Mapping(source = "userPerms.mainPerm", target = "menus"),
    })
    RespLoginDTO.MenusBean createMenusBean(UserPerm userPerm);

    List createMenusBeanChildrenBeans(List perms);

    @Mappings({
            @Mapping(source = "permId", target = "id"),
            @Mapping(source = "permTitle", target = "title"),
            @Mapping(source = "permPath", target = "path")
            //@Mapping(source = "userPerms.mainPerm", target = "menus"),
    })
    RespLoginDTO.MenusBean.ChildrenBean createChildrenBean(Perm perm);

}


@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserPerm {
    /**
     * 主权限
     */
    private Perm mainPerm;
    /**
     * 子权限
     */
    private List childrenPrem;
}
@Data
@EqualsAndHashCode(callSuper = false)
public class Perm implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long permId;
    private Long parentId;
    private String permCode;
    private String permName;
    private LocalDateTime createDate;
    private String permPath;
    private String permTitle;
    private String permIcon;
    private Boolean permType;
}


参考:https://www.cnblogs.com/vb-ahh/p/14836453.html

你可能感兴趣的:(JAVA,spring,boot,java,mybatis)