Spring boot编写VO层的意义

首先要明白,VO层存在的意义,通俗的讲,VO层的存在就是方便前端获取数据,后端将前端的需要的数据做一个整合,打包成一个类。
举一个我第一次使用的小例子,首先看我的数据库类

public class NewsAllInformation {
int id;
String tatil;
String title;
String content;
String image1;
String image2;
String image3;
String image4;
String time;
//set、get方法跳过
}

这是于数据库对应的全部字段,在我我返回的页面中,只需要

 int id;
String title;
String image1;
String image2;
String image3;
String image4;

这几个,这时候我就可以新建一个vo类,存放着几个属性,在service中,做一个替换,换后通过controller层返给前端。

//通过dao层,将所有数据接收,此时 newsAllInformations存放的数据部分是无用的。
	List<NewsAllInformation> newsAllInformations = newsAllInformationMapper.select_1(tatil_1);
//传建一个vo层类的列表,用来接收上面的数据, Lists.newArrayList();是谷歌提供了guava包里面有很多的工具类,需要引依赖
    List<NewsAllInformationVO> newsAllInformationVOS = Lists.newArrayList();
//遍历newsAllInformations,通过NewsAllInformationVOContent方法将newsAllInformations变成newsAllInformationVO并存放到上面创建的vo层类的列表中。
    for(NewsAllInformation newsAllInformation : newsAllInformations){
//遍历之后的每个数据,通过NewsAllInformationVOContent方法生成一个个新						   的newsAllInformationVO数据,然后添加到vo层类的列表中。
NewsAllInformationVO newsAllInformationVO = NewsAllInformationVOContent(newsAllInformation);
    newsAllInformationVOS.add(newsAllInformationVO);}
    return newsAllInformationVOS;

在这里需要在service层的这个类中学一个私有方法来实现这一数据的变换NewsAllInformationVOContent方法

 //返回前端新闻页面数据
private NewsAllInformationVO NewsAllInformationVOContent(NewsAllInformation newsAllInformation){
    NewsAllInformationVO newsAllInformationVO = new NewsAllInformationVO();
    newsAllInformationVO.setImage1(newsAllInformation.getImage1());
    newsAllInformationVO.setImage2(newsAllInformation.getImage2());
    newsAllInformationVO.setImage3(newsAllInformation.getImage3());
    newsAllInformationVO.setImage4(newsAllInformation.getImage4());
    newsAllInformationVO.setTitle(newsAllInformation.getTitle());
    newsAllInformationVO.setId(newsAllInformation.getId());
    return newsAllInformationVO;
}

以上就是我第一次使用vo层的一个心得,还有很多不足之处!

发布了11 篇原创文章 · 获赞 11 · 访问量 216

猜你喜欢

转载自blog.csdn.net/Wangdiankun/article/details/104223921