Entity转VO,DTO神器! mapstruct的使用

Entity转VO,DTO神器! mapstruct的使用

admin 729 2022-08-11

Entity转VO,DTO神器,mapstruct的使用

相关环境依赖

/**
------- 基础环境依赖 -------
pc: win11
jdk: 1.8
maven: 3.6.x
spring boot: 2.7.2

------- 重要依赖 --------
lombok: 1.18.24
mapstruct: 1.4.2.Final
mapstruct-processor: 1.4.2.Final
lombok-mapstruct-binding: 0.2.0

ps: lombok版本大于1.18.12时,会与mapstruct产生冲入,无法的代码中无法为VO,DTO等set值,所以需要引入lombok-mapstruct-binding依赖来解决

场景

我们从数据库查询出数据后,往往需要和其他数据结合形成VO返回给前端,当需要赋值给VO的字段数过多时,重复的写set代码难免过于枯燥,而使用mapstruct进行属性拷贝则可以大大简化转VO的工作量

Entity和VO

// User Model
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
}

// UserVO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserVO {
    private Integer id;
    private String name;
    private String voName;
}

使用mapstruct编写接口

import com.xxx.model.vo.UserVO;
import com.xxx.model.entity.User;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

/**
 * 在项目中 新建一个接口
 *
 * @author xxx
 * @date 2022/8/11 15:47
 * @since 0.1
 */
@Mapper  //注意此处注解来自于:org.mapstruct.Mapper; !!!
public interface UserConverter {
    UserConverter INSTANCE =  Mappers.getMapper(UserConverter.class);
    
    // 起一个方法名,明确参数和返回值,在程序编译的时候会自动在target目录中生成此接口的实现类,并将参数对象中的属性set到返回对象的 同名属性 中去。
    // 此例生成的实现类见文章末尾
    UserVO userToVO (User user);
}

使用

import com.xxx.convert.UserConverter;
import com.xxx.model.vo.UserVO;
import com.xxx.model.entity.User;
import com.xxx.mapper.outer.UserDao;
import com.xxx.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * (User)表服务实现类
 *
 * @author xxx
 * @since 2022-08-04 17:10:14
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public UserVO getName(Integer id){
        User user = this.userDao.getUser(id);
        
        // 直接使用xxxConverter.INSTANCE.方法名(参数)的形式得到转换后的值
        UserVO userVO = UserConverter.INSTANCE.userToVO(user);
        
        System.out.println(user);
        System.out.println("___________");
        System.out.println(userVO);
        
        return userVO;
    }

}

本例中使用mapstruct包的@Mapper注解后 自动生成的UserConverter接口实现类

import com.xxx.model.vo.UserVO;
import com.xxx.model.entity.User;
import javax.annotation.Generated;

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2022-08-11T16:26:29+0800",
    comments = "version: 1.4.2.Final, compiler: javac, environment: Java 1.8.0_241 (Oracle Corporation)"
)
public class UserConverterImpl implements UserConverter {

    @Override
    public UserVO userToVO(User user) {
        if ( user == null ) {
            return null;
        }
        
        UserVO userVO = new UserVO();
        userVO.setId( user.getId() );
        userVO.setName( user.getName() );
        return userVO;
    }
}

更多


# Java # Spring # Spring Boot