modelMapper使用,将数据库查询对象直接转成DTO对象
1.pom引入
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.8</version>
</dependency>
2.将DAO对象转为DTO对象
User user = new User();
user.setId(1L);
user.setNickname("张三");
user.setEmail("101@qq.com");
user.setHonor("测试荣誉");
ModelMapper modelMapper = new ModelMapper();
UserDTO userDTO = modelMapper.map(user, UserDTO.class);
System.out.println(userDTO);
3.工具类
public class ModuleHelper {
private static final ModelMapper modelMapper;
static {
modelMapper = new ModelMapper();
// modelMapper.createTypeMap(String.class, Date.class);
// modelMapper.addConverter(toStringDate);
// modelMapper.getTypeMap(String.class, Date.class).setProvider(localDateProvider);
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
}
private ModuleHelper() {
}
public static <D, T> D map(final T entity, Class<D> outClass) {
return modelMapper.map(entity, outClass);
}
public static <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
return entityList.stream()
.map(entity -> map(entity, outCLass))
.collect(Collectors.toList());
}
public static <S, D> D map(final S source, D destination) {
modelMapper.map(source, destination);
return destination;
}
}
原创:做时间的朋友
分类:
数据转换
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 我在厂里搞 wine 的日子
· 如何通过向量化技术比较两段文本是否相似?
· 35+程序员的转型之路:经济寒冬中的希望与策略
· JavaScript中如何遍历对象?
· 领域模型应用
· 独立开发,这条路可行吗?
· Java简历、面试、试用期、转正
· C#源生成器:让你的代码飞起来的黑科技
· SpringBoot3 + LangChain4j + Redis 实现大模型多轮对话及工具调用
· Java开发AI项目,太爽了!LangChain4j保姆级教程