1、以前我都是直接用spring提供的:BeanUtils.copyProperties(entuty, vo1);方法去转换。
2、后面又学到了转换hutool工具类的转换方法。
3、现在又学了一个利用mapstruct框架转换。
package com.jsrDom.controller;import cn.hutool.core.bean.BeanUtil; import com.jsrDom.converter.TestUserConverter; import com.jsrDom.pojo.entity.MyUserEntity; import com.jsrDom.pojo.vo.MyUserVO; import lombok.RequiredArgsConstructor; import org.springframework.beans.BeanUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList; import java.util.Arrays; import java.util.List;/*** @program: springBoot* @author: quxiao* @create: 2024-04-08 09:42**/ @RestController @RequiredArgsConstructor public class t1 {private final TestUserConverter testUserConverter;@GetMapping("/test1")public void test1() {MyUserEntity entuty = new MyUserEntity("qx", 10);MyUserVO vo1 = new MyUserVO();//spring提供的方法BeanUtils.copyProperties(entuty, vo1);//mapstruct提供的MyUserVO vo = testUserConverter.UserToVO(entuty);System.out.println(vo);System.out.println(vo1);}@GetMapping("/test2")public void test3() {List<MyUserEntity> list = new ArrayList<>(Arrays.asList(new MyUserEntity("1", 1), new MyUserEntity("1", 1), new MyUserEntity("1", 1)));List<MyUserVO> vos1 = testUserConverter.UsersToVOs(list);vos1.stream().forEach(e -> System.out.println(e));System.out.println("-----------------------");//hutool提供的BeanUtil.copyToList(list, MyUserVO.class).stream().forEach(e -> System.out.println(e));} }
package com.jsrDom.converter;import com.jsrDom.pojo.entity.MyUserEntity; import com.jsrDom.pojo.vo.MyUserVO; import org.mapstruct.Mapper;import java.util.List;/*** mapstruct方法**/ @Mapper(componentModel = "spring") public interface TestUserConverter {MyUserVO UserToVO(MyUserEntity entity);List<MyUserVO> UsersToVOs(List<MyUserEntity> list); }
<dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct</artifactId><version>1.5.0.RC1</version></dependency><dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct-jdk8</artifactId><version>1.5.0.RC1</version></dependency><dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct-processor</artifactId><version>1.5.0.RC1</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.12</version></dependency>
使用mapstruct利用了spring的代理模式,将接口补充一个对应的转换方法,在构建时可以查看到