【微服务】springboot整合对象映射工具MapStruct使用详解
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
// 定义实体类UserDTO和User之间的映射关系
@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
@Mapping(source = "userId", target = "id")
@Mapping(source = "userName", target = "name")
UserDTO userToUserDTO(User user);
@Mapping(source = "id", target = "userId")
@Mapping(source = "name", target = "userName")
User userDTOToUser(UserDTO userDTO);
}
// 使用MapStruct映射工具类
public class ExampleUsage {
public static void main(String[] args) {
User user = new User();
user.setId(1L);
user.setName("Alice");
UserDTO userDTO = UserMapper.INSTANCE.userToUserDTO(user);
// 此时userDTO中的属性为userId和userName
User userConverted = UserMapper.INSTANCE.userDTOToUser(userDTO);
// 此时userConverted中的属性为id和name
}
}
这个代码示例展示了如何在Spring Boot项目中使用MapStruct来简化对象映射的过程。首先定义了两个简单的实体类User和UserDTO,然后创建了一个MapStruct映射器接口UserMapper,用于定义User和UserDTO之间转换的规则。最后,在ExampleUsage类的main方法中演示了如何使用这个映射器来转换对象。
评论已关闭