Mapstruct 可以用来处理java实体间的转换,比如DTO转DO,DO转DTO。
Pom依赖如下
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.2.0.Final</version>
<scope>provided</scope>
</dependency>
public class BooleanIntegerMapper {
public int asInt(boolean success) {
return success ? 1 : 0;
}
public boolean asBoolean(int success) {
return success == 1;
}
}
@Mapper(uses = { BooleanIntegerMapper.class })
public interface FaultyMachineMapper {
FaultyMachine doToDTO(FaultyMachineDO FaultyMachineDO);
CloudboxFaultyMachineDO dtoToDO(FaultyMachine faultyMachine);
List<FaultyMachine> dosToDTOs(Iterable<FaultyMachineDO> faultyMachineDOS);
}
Mapstruct会为FaultyMachineMapper生成实现类FaultyMachineMapperImpl,在工程的target目录下可以看到。Spring初始化时会实例化FaultyMachineMapperImpl对象,并且注入到需要使用的地方。
代码中的使用
public class FaultyMachineRepositoryImpl implements FaultyMachineRepository {
private FaultyMachineMapper faultyMachineMapper = Mappers.getMapper(FaultyMachineMapper.class);
@Setter
private FaultyMachineDAO faultyMachineDAO;
@Override
public FaultyMachine getById(int id) {
FaultyMachineDO faultyMachineDO = faultyMachineDAO.getById(id);
FaultyMachine faultyMachine = faultyMachineMapper.doToDTO(faultyMachineDO);
return faultyMachine;
}
@Override
public int insertFaultyMachine(FaultyMachine faultyMachine) {
FaultyMachineDO faultyMachineDO = faultyMachineMapper.dtoToDO(faultyMachine);
return (int)faultyMachineDAO.insertFaultyMachine(faultyMachineDO);
}
}
如果Java类中有一个字段是boolean类型的,对应DB中类型是tinyint,此时使用BeanUtil在DTO和DO之间copy时会报错提示参数类型不匹配。
使用以上的方式就不存在这个问题。