MapStruct集成及使用
文章目录
集成方式
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
- 引入 MapStructjar
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
使用方式
- 定义基类
public interface BaseMapStruct<D, E> {
/**
* DTO转Entity
*
* @param dto
* @return
*/
E toEntity(D dto);
/**
* Entity转DTO
*
* @param entity
* @return
*/
@Named(value = "useMe")
D toDto(E entity);
/**
* DTO集合转Entity集合
*
* @param dtoList
* @return
*/
List<E> toEntity(List<D> dtoList);
/**
* Entity集合转DTO集合
*
* @param entityList
* @return
*/
@IterableMapping(qualifiedByName = "useMe")
List<D> toDto(List<E> entityList);
}
- 创建具体映射对象,及一些关联对象
@Mapper
public interface OrderMapper extends BaseMapStruct<ItemDTO, Item> {
OrderMapper INSTANCE = Mappers.getMapper(OrderMapper.class);
@Mappings({
@Mapping(source = "birthday", target = "birth"),
@Mapping(source = "birthday", target = "birthDateFormat", dateFormat = "yyyy-MM-dd HH:mm:ss"),
@Mapping(target = "birthExpressionFormat", expression = "java(org.apache.commons.lang3.time.DateFormatUtils.format(person.getBirthday(),\"yyyy-MM-dd HH:mm:ss\"))"),
@Mapping(target = "birthValue", expression = "java(person.getBirthday().getTime())"),
@Mapping(target = "id", ignore = true) // 忽略id,不进行映射
})
ItemDTO domain(Item person);
}
@Data
@Accessors(chain = true)
public class Item {
private String itemName;
private Long price;
private Date birthday;
private Integer id;
}
@Data
@Accessors(chain = true)
public class ItemDTO {
private String itemName;
private Long price;
private String birthDateFormat;
private Date birth;
private String birthExpressionFormat;
private Long birthValue;
private Integer id;
}
- 使用
@Slf4j
public class MapStructTest {
@Test
public void test() {
var i = OrderMapper.INSTANCE.domain(new Item().setItemName("test")
.setId(111)
.setBirthday(new Date())
.setPrice(111L));
System.out.println(JsonUtils.toJSONString(i));
var d = OrderMapper.INSTANCE.toEntity(i);
System.out.println(JsonUtils.toJSONString(d));
}
}
文章作者 pengxiaochao
上次更新 2022-10-22
许可协议 不允许任何形式转载。