mapstruct上手

Author Avatar
丁起男 10月 29,2020
  • 在其它设备中阅读本文章

mapstruct上手

导入依赖

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

创建实体类

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserPO {
    private Integer id;
    private String name;
    
    private Date createTime;
    
    private String mag;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserVO {
    private Integer id;
    private String username;
    
    private String createTime;
}

组合bean时使用:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User2PO {
    private String mag;
}

创建转换接口

@Mapper
public interface UserCoverBasic {
    
    UserCoverBasic COVERT = Mappers.getMapper(UserCoverBasic.class);

    //转换单个bean
    @Mappings({
        	//转换名称不同的字段
            @Mapping(source = "name",target = "username"),
        	//转换类型不同的字段
            @Mapping(target = "createTime",expression = "java(userPO.getCreateTime().toString())")
    })
    UserVO toConvertVO(UserPO userPO);
    
    //转换集合bean:本质上就是循环调用单个bean的转换
    List<UserVO> toConvertVOs(List<UserPO> userPOList);
    
    //转换组合bean
    @Mapping(source = "userPO.name",target = "username")
    UserVO toConvertBO(UserPO userPO, User2PO user2PO);
}

测试

//测试单个bean转换
@Test
void test1(){
    UserPO userPO = UserPO.builder()
            .id(1)
            .name("user1")
        	.createTime(new Date())
            .build();
    UserVO userVO = UserCoverBasic.COVERT.toConvertVO(userPO);
    System.out.println(userVO);
    //输出 :UserVO(id=1, username=user1, createTime=Thu Oct 29 11:50:46 CST 2020)
}
//测试集合bean转换
@Test
void test2(){
    List<UserPO> userPOList = new ArrayList<>(){{
        add(UserPO.builder().id(1).name("user1").createTime(new Date()).build());
        add(UserPO.builder().id(2).name("user2").createTime(new Date()).build());
    }};
    List<UserVO> userVOS = UserCoverBasic.COVERT.toConvertVOs(userPOList);
    userVOS.forEach(System.out::println);
    //输出:
    //UserVO(id=1, username=user1, createTime=Thu Oct 29 11:52:00 CST 2020)
	//UserVO(id=2, username=user2, createTime=Thu Oct 29 11:52:00 CST 2020)
}
//测试组合bean转换
@Test
void test3(){
	UserPO userPO = UserPO.builder().id(1).name("user1").createTime(new Date()).build();
    User2PO user2PO = User2PO.builder().mag("123").build
        
    UserVO userVO = UserCoverBasic.COVERT.toConvertBO(userPO, user2PO);
    System.out.println(userVO);
    //输出:UserVO(id=1, username=user1, createTime=2020/10/29 下午2:13, mag=123)
}