博客
关于我
实体类转化为VO返回给前端的方法
阅读量:371 次
发布时间:2019-03-04

本文共 2117 字,大约阅读时间需要 7 分钟。

返回给前端的时候,我以前一直都是直接用实体类entity直接返回的。但是到后面我越来越发现这样子很不方便:

  1. 比如这个实体类中有许多属性我不想返回给前端,那我只好写个null;
  2. 我要一次查询多张表,返回许多数据的话,就肯定只能多去封装一个大类,也就是VO类

其实这里的方法有几种,最普通的及时一个个set了:

以遍历集合为例:

①遍历出来后取出每个元素,一个个set后再添加到新的集合里

//普通类型        List
phoneCategoryList = phoneCategoryRepository.findAll(); //常规写法 List
phoneCategoryVOList = new ArrayList<>(); for (PhoneCategory phoneCategory : phoneCategoryList) { PhoneCategoryVO phoneCategoryVO = new PhoneCategoryVO(); phoneCategoryVO.setCategoryName(phoneCategory.getCategoryName()); phoneCategoryVO.setCategoryType(phoneCategory.getCategoryType()); phoneCategoryVOList.add(phoneCategoryVO); }

②用Java8的lambda表达式:

List
phoneCategoryVOList = phoneCategoryList.stream() .map(e -> new PhoneCategoryVO( e.getCategoryName(), e.getCategoryType() )).collect(Collectors.toList());

③使用commons-lang3或者直接org.springframework.beans. BeanUtils的copyProperties方法:

List
phoneInfoVOList = new ArrayList<>(); for (PhoneInfo phoneInfo : phoneInfoList) { PhoneInfoVO phoneInfoVO = new PhoneInfoVO(); //将phoneSpecs中与phoneSpecsVO属性相同的进行拷贝给VO BeanUtils.copyProperties(phoneInfo,phoneInfoVO); //如果还有不同进行手动赋值 phoneInfoVO.setTag(PhoneUtil.createTag(phoneInfo.getPhoneTag())); phoneInfoVOList.add(phoneInfoVO); }

注意如果实体类中有不想赋值的属性,可以使用copyProperties(Object source, Object target, String... ignoreProperties),后面加上忽略的名字;

上面的方法对应的lambda式为:

List
phoneInfoVOList = phoneInfoList.stream() .map(e -> new PhoneInfoVO( e.getPhoneId(), e.getPhoneName(), e.getPhonePrice()+".00", e.getPhoneDescription(), PhoneUtil.createTag(e.getPhoneTag()), e.getPhoneIcon() )).collect(Collectors.toList());

可以看出在这种情况下,lambda表达式要手动的赋值,而使用BeanUtils的copyProperties方法就可以简洁。不过如果说返回给前端的VO和实体类的属性并不一样的话,使用lambda表达式就更加方便了。

当然,我对于lambda表达式还不够熟练,这个就只能多练习了!

转载地址:http://bxyg.baihongyu.com/

你可能感兴趣的文章
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>