千家信息网

如何mapStruct java bean映射工具

发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,本篇文章为大家展示了如何mapStruct java bean映射工具,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。一、实体模型public class Us
千家信息网最后更新 2025年12月02日如何mapStruct java bean映射工具

本篇文章为大家展示了如何mapStruct java bean映射工具,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

一、实体模型

public class User {    private Integer id;    private String name;    private double account;    private boolean married;//  setters, getters, toString()}public class Employee {    private int id;    private String ename;    private String position;    private String married;//  setters, getters, toString()}

二、分析与实现

最愚蠢的方式是自己写一堆的setter方法与getter方法,大量get/set代码堆积,增加了代码长度和阅读代码的难度。利用工具BeanUtils是可以处理第一个需求的,但第三种需求就无能为力了。这时MapStrut就派上用场了,最简单的配置可以像下面这样:

@Mapperpublic interface UserMapper {    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);    Employee userToEmployee(User user);    User employeeToUser(Employee employee);}

对于第二个需求,可以通过下面方式实现,注解@Mapping可以指定需要把哪个字段source转换为哪个字段target。

@Mapperpublic interface UserMapper {    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);    @Mappings({        @Mapping(source="name", target="ename")    })    Employee userToEmployee(User user);    @Mappings({        @Mapping(source="ename", target="name")    })    User employeeToUser(Employee employee);}

第三个需求有点变态,但是真实发生在我们的项目中,实现起来确实繁琐一些:
首先,自定义转化逻辑,布尔值到字符串,布尔的true对应字符串的Y,布尔的false对应字符串的N:

public class UserTransform {    public String booleanToString(boolean value){        if(value){            return "Y";        }        return "N";    }    public boolean strToBoolean(String str){        if ("Y".equals(str)) {            return true;        }        return false;    }}

使用很简单,在接口的注解Mapper添加uses参数,值就是需要刚才的转换逻辑类。

@Mapper(uses = UserTransform.class)public interface UserMapper {...}

三、结果与分析

用Junit Test写两个测试方法,分别测试User 对象转换Employee ,Employee 对象转换User。

public class MidTest {    @Test    public void midTest(){        User user = new User();        user.setId(125);        user.setName("Lee");        user.setMarried(true);        Employee e = UserMapper.INSTANCE.userToEmployee(user);        System.out.println(e);    }    @Test    public void midTest2(){        Employee e = new Employee();        e.setId(222);        e.setEname("Chao");        e.setMarried("N");        User u = UserMapper.INSTANCE.employeeToUser(e);        System.out.println(u);    }}

上述内容就是如何mapStruct java bean映射工具,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。

0