定义一个基础接口
package com.example.mapstruct;
import org.mapstruct.Named;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;
/**
* @Author zmn @Date 2024/11/27 11:17 @Version 1.0
*/
public interface BaseConverter<DTO, DB> {
DTO do2Dto(DB db);
List<DTO> dosToDtos(List<DB> dbs);
@Named("localDateToLocalDateTime")
default LocalDateTime localDateToLocalDateTime(LocalDate date) {
return date.atStartOfDay();
}
@Named("localDateTimeToDate")
default Date localDateTimeToDate(LocalDateTime localDateTime) {
if (null == localDateTime) {
return null;
}
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
@Named("localDateToDate")
default Date localDateTimeToDate(LocalDate localDateTime) {
if (null == localDateTime) {
return null;
}
ZonedDateTime zonedDateTime = localDateTime.atStartOfDay().atZone(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
}
定义 dtoA 和dtoB 将dtoA 转成B(属性名不一样属性类型不一样)
@Data
public class BeanA {
private LocalDate localDate;
}
@Data
public class BeanB {
private LocalDateTime localDateTime;
}
@Mapper
public interface DtoBeanConverter extends BaseConverter<BeanB, BeanA> {
DtoBeanConverter INSTANCE = Mappers.getMapper(DtoBeanConverter.class);
@Mappings({
@Mapping(
source = "localDate",
target = "localDateTime",
qualifiedByName = "localDateToLocalDateTime")
})
BeanB do2Dto(BeanA beanA);
}
注意
1、在 POM中添加lombok一定在前才能生成DtoBeanConverterImpl
2、LocalDateTime 日期类型来自同一个包
<plugin>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
或者单独定义
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateMapper {
// 将 LocalDateTime 转换为 Date
public Date map(LocalDateTime value) {
if (value == null) {
return null;
}
return Date.from(value.atZone(ZoneId.systemDefault()).toInstant());
}
}
在类中使用
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper(uses = DateMapper.class)
public interface MyMapper {
MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);
@Mapping(source = "dateTime", target = "dateTime")
Target map(Source source);
}