当前位置: 代码网 > it编程>编程语言>Java > Java MapStruct使用配置实战指南

Java MapStruct使用配置实战指南

2025年11月06日 Java 我要评论
一、mapstruct 简介mapstruct是一个编译期注解处理器,它会在编译时自动生成类型安全、无反射的 java bean 映射代码。核心优势:高性能:无运行时反射,生成代码直接调用 gette

一、mapstruct 简介

mapstruct 是一个编译期注解处理器,它会在编译时自动生成类型安全、无反射的 java bean 映射代码。
核心优势:

  • 高性能:无运行时反射,生成代码直接调用 getter/setter。
  • 类型安全:编译期检查,映射出错时编译直接报错。
  • 易于集成:只需引入依赖,配合注解即可。

二、mapstruct 工作原理

  1. 编写 mapper 接口,使用 @mapper 注解。
  2. 编译时,mapstruct 的注解处理器根据接口定义自动生成实现类(通常在 target/generated-sources/annotations 下)。
  3. 运行时,调用自动生成的实现类进行对象转换。

三、快速入门示例

1. 添加依赖

maven:

<dependency>
    <groupid>org.mapstruct</groupid>
    <artifactid>mapstruct</artifactid>
    <version>1.5.5.final</version>
</dependency>
<dependency>
    <groupid>org.mapstruct</groupid>
    <artifactid>mapstruct-processor</artifactid>
    <version>1.5.5.final</version>
    <scope>provided</scope>
</dependency>

2. 定义源对象和目标对象

// entity
public class userentity {
    private long id;
    private string name;
    private string email;
    // getter/setter
}
// dto
public class userdto {
    private long id;
    private string name;
    // getter/setter
}

3. 编写 mapper 接口

import org.mapstruct.mapper;
import org.mapstruct.factory.mappers;
@mapper
public interface usermapper {
    usermapper instance = mappers.getmapper(usermapper.class);
    userdto entitytodto(userentity entity);
    userentity dtotoentity(userdto dto);
}

4. 使用 mapper

userentity entity = new userentity();
entity.setid(1l);
entity.setname("tom");
entity.setemail("tom@example.com");
userdto dto = usermapper.instance.entitytodto(entity);
// dto.id = 1, dto.name = "tom"

四、进阶用法

1. 字段名不一致

public class userentity {
    private string username;
    //...
}
public class userdto {
    private string name;
    //...
}
@mapper
public interface usermapper {
    @mapping(source = "username", target = "name")
    userdto entitytodto(userentity entity);
}

2. 嵌套对象映射

public class addressentity { ... }
public class addressdto { ... }
public class userentity {
    private addressentity address;
}
public class userdto {
    private addressdto address;
}
@mapper
public interface usermapper {
    userdto entitytodto(userentity entity);
}

mapstruct 会自动递归调用同名映射方法。

3. 集合映射

list<userdto> entitylisttodtolist(list<userentity> entities);

4. 自定义转换

@mapper
public interface usermapper {
    @mapping(target = "createtime", expression = "java(new java.util.date())")
    userdto entitytodto(userentity entity);
}

五、常见问题

  • 生成代码找不到?
    • 检查 ide 的 annotation processing 是否开启,代码在 target/generated-sources/annotations 下。
  • 自定义方法怎么用?
    • 可以在 mapper 里定义 default 方法,或用 @named 结合 @mapping 的 qualifiedbyname
  • 与 spring 集成?
    • 用 @mapper(componentmodel = "spring"),mapper 会注册为 spring bean,可自动注入。

六、mapstruct 与 beanutils/dozer/modelmapper 比较

框架性能类型安全反射编译期检查代码生成
mapstruct很高
beanutils一般
dozer较低
modelmapper较低

七. spring 集成与依赖注入

让 mapper 变成 spring bean,只需加 @mapper(componentmodel = "spring")

@mapper(componentmodel = "spring")
public interface usermapper {
    userdto entitytodto(userentity entity);
}

然后就可以在 spring 中自动注入:

@autowired
private usermapper usermapper;

如果 mapper 之间有依赖,可以直接注入其他 mapper:

@mapper(componentmodel = "spring", uses = {addressmapper.class})
public interface usermapper { ... }

八. 多级嵌套对象映射

比如 dto 和 entity 里都包含 address 对象:

public class userentity {
    private addressentity address;
}
public class userdto {
    private addressdto address;
}
@mapper
public interface addressmapper {
    addressdto entitytodto(addressentity entity);
}
@mapper(uses = {addressmapper.class})
public interface usermapper {
    userdto entitytodto(userentity entity);
}

mapstruct 会自动调用 addressmapper 的方法。

九. 枚举类型映射

如果枚举名一致,mapstruct 会自动映射;如果不一致,可以手动指定:

public enum statusenum { enabled, disabled }
public enum statusdto { on, off }
@mapper
public interface statusmapper {
    @mapping(source = "enabled", target = "on")
    @mapping(source = "disabled", target = "off")
    statusdto todto(statusenum status);
}

十. 自定义类型转换(qualifiedbyname、@named)

比如把 string 转成 date:

@mapper
public interface usermapper {
    @mapping(source = "datestr", target = "date", qualifiedbyname = "stringtodate")
    userdto entitytodto(userentity entity);
    @named("stringtodate")
    default date stringtodate(string datestr) {
        // 你自己的转换逻辑
        return new simpledateformat("yyyy-mm-dd").parse(datestr);
    }
}

十一. 更新已有对象(@mappingtarget)

有时需要把 dto 的值“更新”到已存在的 entity:

@mapper
public interface usermapper {
    void updateentityfromdto(userdto dto, @mappingtarget userentity entity);
}

这样不会新建对象,而是直接修改传入的 entity。

十二. 表达式与常量映射

如果目标字段是常量或需要表达式:

@mapper
public interface usermapper {
    @mapping(target = "status", expression = "java(entity.isactive() ? \"active\" : \"inactive\")")
    @mapping(target = "role", constant = "user")
    userdto entitytodto(userentity entity);
}

十三. 映射继承与多态

可以通过接口继承复用映射:

@mapper
public interface basemapper<e, d> {
    d todto(e entity);
    e toentity(d dto);
}
@mapper
public interface usermapper extends basemapper<userentity, userdto> { }

十四. 常见坑及调试方法

  • ide未生成 mapper 实现类?
    • 检查 annotation processing 是否打开,maven/idea/vscode 都要设置。
  • 字段名不一致未映射?
    • 用 @mapping(source, target) 明确指定。
  • 集合、嵌套类型未自动转换?
    • 检查是否正确配置 uses,相关 mapper 是否存在。
  • 调试生成代码?
    • 直接到 target/generated-sources/annotations 查看生成的实现类,理解 mapstruct 的处理逻辑。
  • 复杂类型转换报错?
    • 用 @namedqualifiedbyname 明确指定转换方法。

十五、其他扩展

1. localdate/localdatetime 映射

场景:dto 里是 string,entity 里是 localdate

public class userentity {
    private localdate birthday;
}
public class userdto {
    private string birthday; // "2024-07-11"
}

mapper 写法:

@mapper
public interface usermapper {
    @mapping(source = "birthday", target = "birthday", qualifiedbyname = "stringtolocaldate")
    userentity dtotoentity(userdto dto);
    @named("stringtolocaldate")
    default localdate stringtolocaldate(string datestr) {
        return localdate.parse(datestr);
    }
}

反向转换:

@mapping(source = "birthday", target = "birthday", qualifiedbyname = "localdatetostring")
@named("localdatetostring")
default string localdatetostring(localdate date) {
    return date != null ? date.tostring() : null;
}

2. bigdecimal 映射

场景:dto 是 string 或 double,entity 是 bigdecimal

public class productentity {
    private bigdecimal price;
}
public class productdto {
    private string price;
}

mapper 写法:

@mapper
public interface productmapper {
    @mapping(source = "price", target = "price", qualifiedbyname = "stringtobigdecimal")
    productentity dtotoentity(productdto dto);
    @named("stringtobigdecimal")
    default bigdecimal stringtobigdecimal(string price) {
        return price != null ? new bigdecimal(price) : null;
    }
}

反向同理,写个 bigdecimaltostring 方法。

3. 枚举类型映射

场景:dto 和 entity 枚举名不同/枚举类型不同。

public enum statusentity { enabled, disabled }
public enum statusdto { on, off }

mapper 写法:

@mapper
public interface statusmapper {
    @mapping(source = "enabled", target = "on")
    @mapping(source = "disabled", target = "off")
    statusdto todto(statusentity status);
}

或者用自定义方法:

@named("statustodto")
default statusdto statustodto(statusentity status) {
    switch (status) {
        case enabled: return statusdto.on;
        case disabled: return statusdto.off;
        default: return null;
    }
}

4. 嵌套集合映射

场景:dto 和 entity 都有嵌套集合,如 list、set。

public class orderentity {
    private list<itementity> items;
}
public class orderdto {
    private list<itemdto> items;
}

mapper 写法:

@mapper
public interface itemmapper {
    itemdto entitytodto(itementity entity);
}
@mapper(uses = itemmapper.class)
public interface ordermapper {
    orderdto entitytodto(orderentity entity);
    list<orderdto> entitylisttodtolist(list<orderentity> entities);
}

mapstruct 会自动将集合中的每个元素递归映射。

5. 常见 mapstruct 报错及解决

(1)找不到映射方法

报错内容:

no property named 'xxx' exists in source parameter(s).

原因: dto/entity 字段名不一致或拼写错误。
解决: 用 @mapping(source = "xxx", target = "yyy") 显式指定。

(2)类型不兼容

报错内容:

can't map property "java.lang.string price" to "java.math.bigdecimal price".

原因: mapstruct 不知道怎么转换 string 到 bigdecimal。
解决: 写自定义转换方法,并用 qualifiedbyname 指定。

(3)嵌套集合或对象未自动映射

报错内容:

no implementation for method entitytodto(itementity entity) found.

原因: itemmapper 没有被 uses 引用,或没有实现方法。
解决: 在主 mapper 上加 uses = {itemmapper.class},并实现相关方法。

(4)编译未生成实现类

原因: idea/maven 未开启 annotation processing。
解决:

  • idea: settings -> build, execution, deployment -> compiler -> annotation processors -> enable。
  • maven: mvn clean compile,确保 target/generated-sources/annotations 下有实现类。

(5)自定义方法未被调用

原因: 没有用 @named 和 qualifiedbyname 关联。
解决: 方法加 @named("xxx")@mapping 里加 qualifiedbyname = "xxx"

6. 进阶建议

  • 对于复杂类型转换,建议都用 @named 标记方法,方便复用和维护。
  • 对于枚举、日期、金额等类型,推荐写专门的 mapper 或 converter 类。
  • 多层嵌套/集合映射时,合理拆分 mapper,避免主 mapper 过于庞大。

参考示例

@mapper
public interface usermapper {
    @mapping(source = "birthday", target = "birthday", qualifiedbyname = "stringtolocaldate")
    @mapping(source = "balance", target = "balance", qualifiedbyname = "stringtobigdecimal")
    userentity dtotoentity(userdto dto);
    @named("stringtolocaldate")
    default localdate stringtolocaldate(string datestr) {
        return datestr != null ? localdate.parse(datestr) : null;
    }
    @named("stringtobigdecimal")
    default bigdecimal stringtobigdecimal(string val) {
        return val != null ? new bigdecimal(val) : null;
    }
}

到此这篇关于java mapstruct使用配置实战指南的文章就介绍到这了,更多相关java mapstruct使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com