一、maven依赖引入orika
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>1.5.4</version>
</dependency>
二、Orika工具类
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.TypeFactory;
import java.util.List;
public class BeanMapperUtil {
/**
* Mapper factory
*/
private static final MapperFactory NOT_NULL_MAPPER_FACTORY = new DefaultMapperFactory.Builder().mapNulls(false).build();
private BeanMapperUtil() {
}
/**
* Map object
*
* @param source source
* @param destinationClass targetClass
* @return object or null
*/
public static <S, D> D map(S source, Class<D> destinationClass) {
return NOT_NULL_MAPPER_FACTORY.getMapperFacade().map(source, destinationClass);
}
/**
* Map list
*
* @param sourceList sourceList
* @param sourceClass sourceClass
* @param destinationClass destinationClass
* @return List
*/
public static <S, D> List<D> mapList(Iterable<S> sourceList, Class<S> sourceClass, Class<D> destinationClass) {
return NOT_NULL_MAPPER_FACTORY.getMapperFacade().mapAsList(sourceList, TypeFactory.valueOf(sourceClass), TypeFactory.valueOf(destinationClass));
}
}
三、使用示例
准备工作,定义两个对象:
@AllArgsConstructor
@NoArgsConstructor
@Data
public static class User {
private String name;
private Integer age;
}
@ApiModel
@AllArgsConstructor
@NoArgsConstructor
@Data
public static class UserDTO {
@ApiModelProperty("姓名")
private String name;
@ApiModelProperty("年龄")
private Integer age;
}
1、单个对象之间
User user = new User("张三", 18);
//user对象:BeanMapperUtil.User(name=张三, age=18)
System.out.println("user对象:" + user);
UserDTO userDTO = BeanMapperUtil.map(user, UserDTO.class);
//userDTO对象:BeanMapperUtil.UserDTO(name=张三, age=18)
System.out.println("userDTO对象:" + userDTO);
2、对象集合之间
List<User> userList = Lists.newArrayList();
userList.add(new User("张三", 10));
userList.add(new User("李四", 12));
// userList对象:[BeanMapperUtil.User(name=张三, age=10), BeanMapperUtil.User(name=李四, age=12)]
System.out.println("userList对象:" + userList);
List<UserDTO> userDTOList = BeanMapperUtil.mapList(userList, User.class, UserDTO.class);
//userDTOList对象:[BeanMapperUtil.UserDTO(name=张三, age=10), BeanMapperUtil.UserDTO(name=李四, age=12)]
System.out.println("userDTOList对象:" + userDTOList);