Java对象转换框架
引入配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <properties> <org.mapstruct.version>1.5.5.Final</org.mapstruct.version> </properties> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>${org.mapstruct.version}</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>${org.mapstruct.version}</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </dependency>
|
定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @Data @SuperBuilder @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode public class BaseEntity implements Serializable { @ApiModelProperty(value = "主键id") private Long id;
@ApiModelProperty(value = "创建时间") private Date createTime;
@ApiModelProperty(value = "更新时间") private Date updateTime;
@ApiModelProperty(value = "删除标记 0未删除 1已删除") private Integer isDeleted; }
@Data @SuperBuilder @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode public class BaseBO implements Serializable { @ApiModelProperty(value = "主键id") private Long id;
@ApiModelProperty(value = "创建时间") private Date createTime;
@ApiModelProperty(value = "删除") private String delFlag; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import com.java.template.biz.bean.bo.BaseBO; import com.java.template.dal.entity.BaseEntity; import org.mapstruct.Mapper; import org.mapstruct.Mapping;
@Mapper(componentModel = "spring") public interface IBaseEntityConvert {
@Mapping(target = "delFlag", expression = "java(deal(entity.getIsDeleted()))") BaseBO toBO(BaseEntity entity);
default String deal(Integer isDeleted) { return isDeleted == 1 ? "已删除" : "未删除"; } }
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @SpringBootTest public class T { @Resource private IBaseEntityConvert baseEntityConvert;
@Test void t(){ BaseEntity build = BaseEntity.builder().id(1L).createTime(DateUtil.date()).isDeleted(2).build(); BaseEntity build2 = BaseEntity.builder().id(3L).createTime(DateUtil.date()).isDeleted(1).build(); System.out.println(baseEntityConvert.toBO(build)); System.out.println(baseEntityConvert.toBO(build2)); } }
|
其他
IDEA装插件MapStruct Support可以有代码提示功能
参考文档
相关文章
SpringBoot常用注解