DTO、VO、POJO、PO、entity到底用哪个?相互之间如何转换?BeanUtils.copyProperties的使用

tech2025-12-21  0

entity:与数据库字段对应,和数据库交互的对象 PO:和entity一样 VO:和视图交互的对象 DTO:传输时的中间对象 POJO:简单无规则纯的传统意义的java对象、只有属性字段及setter和getter方法

分出这么多种实体类型的好处是各个不同的层与别的层之间进行交互时拥有固定的类型,当某一个层的需求发生变化时,修改对应的实体对象即可,不会影响到其他层。 举个例子,DAO层通过entity与数据库进行交互,从数据库获取到的对象传到controller后悔转换成VO对象与视图层进行交互,这时如果来了一个新的需求,视图需要一个新的字段信息,但是这个字段不是在数据库中的,而是一个固定的值或是通过某些逻辑在业务层算出来的,这时只需要将VO对象新增一个属性,在传给前端时给其对象设置值即可,不用修改DAO层的相关代码。

知道了为什么要分这么多实体类之后就需要知道他们相互之间如何转换,比较常用的是Spring提供的BeanUtils.copyProperties方法

//假设这里有两个实体类StudentEntity和StudentDTO //studentEntity里面存放着从数据库查询出来的信息 StudentDTO studentDTO = new StudentDTO(); BeanUtils.copyProperties(studentEntity,studentDTO);

上面的代码能够将studentEntity中与studentDTO相同属性的值复制到studentDTO中去,至于那些不同的属性则不会管。 既然单个对象的是上面这样,那么如果想要转换List我们加个foreach循环就行了。

//假设这里有两个实体类StudentEntity和StudentDTO //studentEntityList里面存放着从数据库查询出来的信息 List<StudentDTO > studentDTOList = new ArrayList<>(studentEntityList.size()); for(Object obj: studentEntityList){ StudentDTO studentDTO = new StudentDTO(); BeanUtils.copyProperties(obj,studentDTO); studentDTOList.add(studentDTO); }

如果每次转换都要写上这么三四行代码也挺麻烦的,我们可以将其简单的封装一下,以后调用起来就会方便很多。

import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ConversiontUtil { public static <T> T sourceToTarget(Object source, Class<T> target){ if(source == null){ return null; } T targetObject = null; try { targetObject = target.newInstance(); BeanUtils.copyProperties(source, targetObject); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return targetObject; } public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){ if(sourceList == null){ return null; } List targetList = new ArrayList<>(sourceList.size()); try { for(Object source : sourceList){ T targetObject = target.newInstance(); BeanUtils.copyProperties(source, targetObject); targetList.add(targetObject); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return targetList; } }
最新回复(0)