💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**1. 3个存在同名属性也存在不同名属性的实体类** ```java @Data public class Address { private Integer stuId; private String address; } @Data public class Score { private Integer stuId; private Double score; } @Data public class StudentDto { private Integer stuId; private String address; private Double score; } ``` **2. 映射接口** ```java @Mapper public interface StudentMapper { StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class); /** * 1)当source1与source2不存在同名的属性时可以进行自动映射。 * 2)当source1与source2存在同名的属性时则需要明确指定是哪个source。 */ @Mapping(source = "source1.stuId", target = "stuId") StudentDto toDto(Address source1, Score source2); } ``` **3. 测试** ```java @Test public void testStudentMapper() { Address address = new Address(); Score score = new Score(); address.setStuId(1001); address.setAddress("亚洲-中国"); score.setStuId(1002); score.setScore(65.5d); StudentDto studentDto = StudentMapper.INSTANCE.toDto(address, score); //Address:Address(stuId=1001, address=亚洲-中国) System.out.println("Address:" + address); //Score:Score(stuId=1002, score=65.5) System.out.println("Score:" + score); //StudentDto:StudentDto(stuId=1001, address=亚洲-中国, score=65.5) System.out.println("StudentDto:" + studentDto); } ``` **4. 查看映射接口被Mapstruct编译后的代码** ```java public class StudentMapperImpl implements StudentMapper { public StudentMapperImpl() { } public StudentDto toDto(Address source1, Score source2) { if (source1 == null && source2 == null) { return null; } else { StudentDto studentDto = new StudentDto(); if (source1 != null) { studentDto.setStuId(source1.getStuId()); studentDto.setAddress(source1.getAddress()); } if (source2 != null) { studentDto.setScore(source2.getScore()); } return studentDto; } } } ```