Mapstruct 实体属性映射框架

Mapstruct 依赖

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.5.0.Final</version>
</dependency>
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.5.0.Final</version>
</dependency>

简单用法

(1)定义实体类

//定义UserEntity实体和UserPo两个实体
@Data   
public class UserEntity {
    private Long id;
    private Date gmtCreate;
    private Date createTime;
    private Long buyerId;
    private Long age;
    private String userNick;
    private String userVerified;
}
​
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserPo {
    private Long id;
    private Date gmtCreate;
    private Date createTime;
    private Long buyerId;
    private Long age;
    private String userNick;
    private String userVerified;
}

(2)定义转换接口

定义mapstruct接口,在接口上打上@Mapper注解componentModel = "spring"属性表示交给Spring去管理,会在自动生成的实现类上加上@Component注解

注意:@Mapper是Mapstruct的注解,不要引错了

@Mapper(componentModel = "spring")
public interface IUserMapper {
    IUserMapper INSTANCT = Mappers.getMapper(IUserMapper.class);
    UserEntity poToEntity(UserPo userPo);
}

(3)测试一下

UserPo po = UserPo.builder()
                .id(123L)
                .age(12L)
                .createTime(new Date())
                .userNick("张三")
                .buyerId(123456L)
             .build();
UserEntity userEntity = iUserMapper.poToEntity(po);
System.out.println(userEntity);
输出:
UserEntity(id=123, gmtCreate=null, createTime=Tue Jan 09 15:33:51 CST 2024, buyerId=123456, age=12, userNick=张三, userVerified=null)

(4)在target查看在编译时自动生成的实现类

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2024-01-09T15:43:48+0800",
    comments = "version: 1.5.0.Final, compiler: javac, environment: Java 1.8.0_391 (Oracle Corporation)"
)
@Component
public class IUserMapperImpl implements IUserMapper {
​
    @Override
    public UserEntity poToEntity(UserPo userPo) {
        if ( userPo == null ) {
            return null;
        }
​
        UserEntity userEntity = new UserEntity();
​
        userEntity.setId( userPo.getId() );
        userEntity.setGmtCreate( userPo.getGmtCreate() );
        userEntity.setCreateTime( userPo.getCreateTime() );
        userEntity.setBuyerId( userPo.getBuyerId() );
        userEntity.setAge( userPo.getAge() );
        userEntity.setUserNick( userPo.getUserNick() );
        userEntity.setUserVerified( userPo.getUserVerified() );
​
        return userEntity;
    }
}

高级用法

1. 属性名称转换

修改UserEntity属性userNick为userNickChange

@Data
public class UserEntity {
    private Long id;
    private Date gmtCreate;
    private Date createTime;
    private Long buyerId;
    private Long age;
    private String userNickChange;
    private String userVerified;
}

@Mapping注解指定source和target字段名称对应关系

@Mapper(componentModel = "spring")
public interface IUserMapper {
    IUserMapper INSTANCT = Mappers.getMapper(IUserMapper.class);
​
    @Mapping(target = "userNickChange", source = "userNick")
    UserEntity poToEntity(UserPo userPo);
}

📢:String转日期&String转数字&忽略某个字端&给默认值等
 

@Mapping(target = "createTime", source = "createTime", dateFormat = "yyyy-MM-dd")

@Mapping(target = "age", source = "age", numberFormat = "#0.00")
//忽略某个字段
@Mapping(target = "id", ignore = true)
//当userV == null时,给userVerified赋值为defaultValue-2
@Mapping(target = "userVerified", source = "userV" ,defaultValue = "defaultValue-2")
//添加java表达式
@Mapping(target = "userVerified", expression = "expression = "java(Integer.parseInt("1"))"")

2. 自定义转换

如果现有的能力都不能满足需要,可以自定义一个转换器,比如我们需要把一个字符串使用JSON工具转换成对象。

(1)在entity中加入Attributes自定义类型的属性

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Attributes {
    private Long id;
    private String name;
}

@Data
public class UserEntity {
    private Long id;
    private Date gmtCreate;
    private Date createTime;
    private Long buyerId;
    private Long age;
    private String userNick1;
    private String userVerified;
    private Attributes attributes;
}

(2)编写自定义转换处理类

定义一个普通的Java类,要在方法上打上@Named

public class AttributeConvertUtil {
    
    @Named("jsonToObject")
    public Attributes jsonToObject(String jsonStr) {
        if (StringUtils.isEmpty(jsonStr)) {
            return null;
        }
        return JSONObject.parseObject(jsonStr, Attributes.class);
    }

(3)修改转换接口

  • 在@Mapper上引用我们的自定义转换代码类AttributeConvertUtil

@Mapper(componentModel = "spring",uses = AttributeConvertUtil.class)
  • 使用qualifiedByName指定我们使用的自定义转换方法

@Mapper(componentModel = "spring",uses = AttributeConvertUtil.class)
public interface IPersonMapper {
    IPersonMapper INSTANCT = Mappers.getMapper(IPersonMapper.class);

    @Mapping(target = "attributes", source = "attributes", qualifiedByName = "jsonToObject")
    @Mapping(target = "userNick1", source = "userNick")
    @Mapping(target = "createTime", source = "createTime", dateFormat = "yyyy-MM-dd")
    @Mapping(target = "age", source = "age", numberFormat = "#0.00")
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "userVerified", defaultValue = "defaultValue-2")
    UserEntity po2entity(UserPo userPo);
}

3.集合

集合转换会自动找到对应的类型基类做底层转换

@Mapping(target = "userNickChange", source = "userNick")
UserEntity poToEntity(UserPo userPo);

List<UserEntity> poToEntityList(List<UserPo> userPos);

异常

报错:mapstruct 报错 No property named “xxx” exists in source parameter(s). Did you mean “null”

解决:根据官网的指示lombok(版本在1.18.16以上)和mapstruct一起使用时,还需要添加lombok-mapstruct-binding依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok-mapstruct-binding</artifactId>
    <version>0.2.0</version>
</dependency>

  • 28
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值