Java詳解entity轉(zhuǎn)換到vo過程
起因
使用 mybatis-plus 操作后獲得的數(shù)據(jù)類型為 Entity,但是前端界面往往需要展示一些其他的字段數(shù)據(jù),此時(shí)就需要 將 Entity 轉(zhuǎn)化為 Vo。
那么他們?nèi)叩年P(guān)系是什么呢?面向的使用對(duì)象不同
entity: 對(duì)應(yīng)數(shù)據(jù)庫表模型
vo: 對(duì)應(yīng)需要返回到前端的數(shù)據(jù)模型
dto: 對(duì)應(yīng)后臺(tái)內(nèi)部調(diào)用的數(shù)據(jù)模型
package com.springblog.entity.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class BlogVo implements Serializable {
private String title;
/**
* 前端需要展示的其他字段
*/
private String otherProperty;
}package com.springblog.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
@TableName("m_blog")
public class BlogEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String title;
private String description;
private String content;
private LocalDateTime created;
}1. 將Entity轉(zhuǎn)化為Vo
@GetMapping("/one/{id}")
public R oneDefine(@PathVariable(name = "id") Long id) {
BlogEntity blogEntity = blogService.queryBlogById(id);
BlogVo blogVo = new BlogVo();
BeanUtil.copyProperties(blogEntity,blogVo);
blogVo.setOtherProperty("前端展示額外字段");
return R.ok().put("data", blogVo);
}2. 將List<Entity>轉(zhuǎn)換為List<Vo>
如果采用最簡(jiǎn)單粗暴的方式,那么這個(gè)過程應(yīng)該是這樣的:
- 創(chuàng)建一個(gè)臨時(shí)ArrayList
- 遍歷 List ,并在內(nèi)部調(diào)用工具類方法
BeanUtil.copyProperties(source,target)將每一個(gè)Entity轉(zhuǎn)化為vo - 將每一個(gè)復(fù)制轉(zhuǎn)換后的voItem 通過add()方法添加到臨時(shí)創(chuàng)建的List中
過于繁瑣,這很不好
@GetMapping("/list1")
public R list1(@RequestBody Map<String, Object> params) {
QueryWrapper<BlogEntity> queryWrapper = new QueryWrapper<>();
List<BlogEntity> list = blogMapper.selectList(queryWrapper);
ArrayList<BlogVo> voList = new ArrayList<>();
list.forEach(item->{
BlogVo voItem = new BlogVo();
BeanUtil.copyProperties(item,voItem);
voList.add(voItem);
});
return R.ok().put("data", voList);
}封裝到工具類后使用
封裝后,將 Entity 轉(zhuǎn)化為 Vo
@GetMapping("/one/{id}")
public R oneDefine(@PathVariable(name = "id") Long id) {
BlogEntity blogEntity = blogService.queryBlogById(id);
BlogVo blogVo = ConvertUtil.entityToVo(blogEntity, BlogVo.class);
blogVo.setOtherProperty("前端展示額外字段");
return R.ok().put("data", blogVo);
}封裝后,將 List<Entity> 轉(zhuǎn)換為List<Vo>
@GetMapping("/list1")
public R list1(@RequestBody Map<String, Object> params) {
QueryWrapper<BlogEntity> queryWrapper = new QueryWrapper<>();
List<BlogEntity> list = blogMapper.selectList(queryWrapper);
List<BlogVo> blogVos = ConvertUtil.entityToVoList(list, BlogVo.class);
return R.ok().put("data", blogVos);
}
性能以及原理
- 使用Spring提供的BeanUtil在日常使用足夠了,如果涉及到數(shù)據(jù)量很大的情況,復(fù)制就比較耗時(shí)了,推介使用Mapstruct。
- Spring和Apache的BeanUtils則是用到了反射機(jī)制,都是淺拷貝
- MapStruct使用注解處理器生成實(shí)現(xiàn)類,實(shí)現(xiàn)類內(nèi)部是原生的new對(duì)象,然后SetXxx/getXxx方式賦值進(jìn)行數(shù)據(jù)拷貝的,類似lombok
- Apache提供的BeanUtils相對(duì)使用的較少
ConvertUtil工具類源碼
package com.springblog.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @Author ifredom
* @Description 類型轉(zhuǎn)換: Entity - Vo轉(zhuǎn)換
* @Date 2022/5/10 15:59
* @Param [params]
**/
public class ConvertUtil {
public static final Logger logger = LoggerFactory.getLogger(ConvertUtil.class);
public static <T> T entityToVo(Object source, Class<T> target) {
if (source == null) {
return null;
}
T targetObject = null;
try {
targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
} catch (Exception e) {
e.printStackTrace();
}
return targetObject;
}
public static <T> List<T> entityToVoList(Collection<?> sourceList, Class<T> target) {
if (sourceList == null) {
return null;
}
List<T> targetList = new ArrayList<>(sourceList.size());
try {
for (Object source : sourceList) {
T targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
targetList.add(targetObject);
}
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetList;
}
}到此這篇關(guān)于Java詳解entity轉(zhuǎn)換到vo過程的文章就介紹到這了,更多相關(guān)Java entity轉(zhuǎn)vo內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Boot多數(shù)據(jù)源及其事務(wù)管理配置方法
本篇文章主要介紹了Spring Boot多數(shù)據(jù)源及其事務(wù)管理配置方法,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-04-04
java實(shí)現(xiàn)的連接數(shù)據(jù)庫及模糊查詢功能示例
這篇文章主要介紹了java實(shí)現(xiàn)的連接數(shù)據(jù)庫及模糊查詢功能,結(jié)合實(shí)例形式分析了java基于jdbc連接數(shù)據(jù)庫及使用LIKE語句實(shí)現(xiàn)模糊查詢功能的相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
springboot application無法使用$獲取pom變量的問題及解決
這篇文章主要介紹了springboot application無法使用$獲取pom變量的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
idea創(chuàng)建項(xiàng)目沒有webapp文件夾的解決方法
本文主要介紹了idea創(chuàng)建項(xiàng)目沒有webapp文件夾的解決方法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
Java使用Junit4.jar進(jìn)行單元測(cè)試的方法
今天通過本文給大家介紹Java使用Junit4.jar進(jìn)行單元測(cè)試的方法,本文通過圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-11-11
mybatis項(xiàng)目CRUD步驟實(shí)例詳解
這篇文章主要介紹了mybatis項(xiàng)目CRUD步驟,包括pom.xml引入相應(yīng)的依賴,在resources目錄下寫配置文件,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09

