在實際項目中,我們常常需要把兩個相似的對象相互轉換,其目的是在對外提供數據時需要將一部分敏感數據(例如:密碼、加密 token 等)隱藏起來
多用於DTO VO DO 對象轉換
需要用到的jar
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper --> <dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>2.3.8</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
@Data @AllArgsConstructor @NoArgsConstructor public class StudentDTO { private Integer id; private String name; private Integer age; private String email; //訂單號 private String orderNo; }
@Data public class StudentVO { private Integer id; private String name; private Integer age; private String email; }
需求將 DTO 轉換成 VO (對象狀態,集合狀態)
public class MyServiceImpl { public static StudentDTO studentDTO; public static List<StudentDTO> dList; static { studentDTO = new StudentDTO(); studentDTO.setId(111); studentDTO.setName("張三"); studentDTO.setAge(18); studentDTO.setEmail("abe@163.com"); studentDTO.setOrderNo("2020123567"); dList = new ArrayList<StudentDTO>(); StudentDTO s1 = new StudentDTO(222, "lisi", 28, "345@163", "345"); StudentDTO s2 = new StudentDTO(333, "zhaoliu", 38, "567@163", "567"); dList.add(s1); dList.add(s2); } /*** * 方式一 modeMapper 對象狀態 */ @Test public void test() { System.out.println(studentDTO); ModelMapper modelMapper = new ModelMapper(); StudentVO student = modelMapper.map(studentDTO, StudentVO.class); System.out.println(student.toString()); } /*** * 方式一 modeMapper list */ @Test public void test2() { ModelMapper modelMapper = new ModelMapper(); List<StudentVO> vList = modelMapper.map(dList, new TypeToken<List<StudentDTO>>() { }.getType()); System.out.println(vList); } /*** * 方式二 BeanUtils (spring的) 對象狀態 */ @Test public void test3() { StudentVO studentVO = new StudentVO(); BeanUtils.copyProperties(studentDTO,studentVO); System.out.println(studentVO); } /*** * 方式二 BeanUtils (spring的) list */ @Test public void test4() { List<StudentVO> studentVOList = dList.stream().map(t -> { StudentVO studentVO = new StudentVO(); BeanUtils.copyProperties(t, studentVO); return studentVO; }).collect(Collectors.toList()); System.out.println(studentVOList); } }