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層返給前端。

	List<NewsAllInformation> newsAllInformations = newsAllInformationMapper.select_1(tatil_1);

    List<NewsAllInformationVO> newsAllInformationVOS = Lists.newArrayList();

    for(NewsAllInformation newsAllInformation : newsAllInformations){

	    NewsAllInformationVO newsAllInformationVO = NewsAllInformationVOContent(newsAllInformation);
        newsAllInformationVOS.add(newsAllInformationVO);}
    
    return newsAllInformationVOS;

在這裏因爲是處理列表,引用了谷歌的Lists方法創建一個列表數據,然後需要在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層的一個心得,還有很多不足之處!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章