javaBean转换(mapstruct)
2022-02-09 本文已影响0人
阿杰_96c5
添加依赖(解决lombok与mapstruct的冲突)
<properties>
<org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
</dependencies>
<!-- 解决lombok与mapstruct的冲突 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
构建转换工具(属性对照关系)
@Mapper(componentModel = "spring") // 支持spring
public interface KsxxConverter {
KsxxConverter INSTANCE = Mappers.getMapper(KsxxConverter.class);
@Mappings({
// @Mapping(source = "id", target = "departmentId" ),
@Mapping(target = "departmentId" ,expression = "java(Long.parseLong(DaoHelper.getSeq()))"),// 根据表达式代码生成目标对象ID
@Mapping(source = "ksmc", target = "departmentName"),
@Mapping(source = "ksjj",target = "departmentDesc"),
@Mapping(source = "cjsj", target = "insertDt"),
// @Mapping(source = "sjks", target = ""),
// @Mapping(source = "pym", target = ""),
@Mapping(source = "gxsj", target = "updateDt"),
@Mapping(target = "hospitalId" ,expression = "java(21122415521000366L)"),
@Mapping(target = "isVirtual" ,expression = "java(1)"),
})
Department toDepartment(Ksxx ksxx); // 对象转换
List<Department> toDepartmentList(List<Ksxx> ksxxes); // 列表转换
}
调用转换工具
@Test
void testKsxxDao(){
List<Ksxx> ksxxes = ksxxDao.queryAll(null);
ksxxes.forEach(System.out::println);
System.out.println("=======================================");
List<Department> departments = KsxxConverter.INSTANCE.toDepartmentList(ksxxes);
departments.forEach(System.out::println);
}