ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
**1. 两个实体类** ```java @Builder @Data public class Nurse { private Integer id; private String name; } @Builder @Data public class NurseDto { private Integer id; private String name; } ``` **2. 映射接口** ```java @Mapper public interface NurseMapper { NurseMapper INSTANCE = Mappers.getMapper(NurseMapper.class); /** * id的取值为constant。 * 当s.name为null时,name的取值为defaultValue */ @Mapping(target = "id", constant = "-1000") @Mapping(source = "s.name", target = "name", defaultValue = "没有这个人!") NurseDto toDto(Nurse s); } ``` **3. 测试** ```java @Test public void testNurseMapper() { Nurse nurse = Nurse.builder().id(1001).name(null).build(); NurseDto nurseDto = NurseMapper.INSTANCE.toDto(nurse); //Nurse:Nurse(id=1001, name=null) System.out.println("Nurse:" + nurse.toString()); //NurseDto:NurseDto(id=-1000, name=没有这个人!) System.out.println("NurseDto:" + nurseDto.toString()); } ``` **4. 查看被MapStruct编译后的代码** ```java public class NurseMapperImpl implements NurseMapper { public NurseMapperImpl() { } public NurseDto toDto(Nurse s) { if (s == null) { return null; } else { NurseDtoBuilder nurseDto = NurseDto.builder(); if (s.getName() != null) { nurseDto.name(s.getName()); } else { nurseDto.name("没有这个人!"); } nurseDto.id(-1000); return nurseDto.build(); } } } ```