惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
Jina AI
Jina AI
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
Recent Announcements
Recent Announcements
I
InfoQ
L
LangChain Blog
The Cloudflare Blog
IT之家
IT之家
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
博客园 - 聂微东
美团技术团队
博客园_首页

博客园 - Augur

又开始使用,学习 Integer和int Mybatis的学习1 初次安装与错误排除 知乎的 Java开发中的23种设计模式(转) entityVo对象与entity对象 dao 网上Java总结 dto vo html css col-md-offset VUE - 相对路径 转:防止跨站攻击,安全过滤 Java中的包装数据类型 一些名词 数据表 键值定义 mysql 表结构 楚乔传 Princess Agents Java学习08 (第一遍) - SpringMVC
vo与po
Augur · 2017-12-14 · via 博客园 - Augur

 场景:

控制层使用vo对象,数据层使用po对象,业务层负责将po对象转换成vo对象传递给控制层
vo和po对象之间转换可以用BeanUtils.copyProperties(vo, po);方法
如果数据层传递的是要给集合对象,譬如List集合,我是这么写的

Java code

?

1

2

3

4

5

6

7

8

List<DeptVO> voList=new ArrayList<DeptVO>();

List<DetPO> poList=dao.list();

DepartmentVO vo=null;

for(DeptPO po:poList){

    vo=new DepartmentVO();

    BeanUtils.copyProperties(vo, po);

    voList.add(vo);

}


结果符合需求,但是每个业务模块都使用这种写法,感觉效率太低了,
各位有没有好的解决方案或思路,能给介绍下,万分感谢

如果是spring的话可以采用AOP解决,可以将你的业务方法的返回值改为object,然后将需要转换的业务方法定义为切入点,使用spring的环绕增强 ,切入点你可以在spring的配置文件中定义

1

2

3

4

5

6

7

8

//通过MethodInterfceptor实现环绕增强,关键代码如下

public Object invoke(MethodInvocation invocation) throws Throwable{

try{

            List<DeptVO> voList=new ArrayList<DeptVO>();

              Object po=invocation.proceed();  //调用目标方法

              BeanUtils.copyProperties(vo, po); 

       }

  return  voList;//将你转换的后的对象返回出去 

}

自己写了个公共方法,勉强能用,分享下

Java code

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public static List copyList (List <? extends Object> poList , Class voClass){

        List voList=new ArrayList();

        Object voObj =null;

        for(Object poObj:poList){

            try {

                voObj = voClass.newInstance();

            } catch (InstantiationException | IllegalAccessException e) {

                e.printStackTrace();

            }

            BeanUtils.copyProperties(poObj, voObj);

            voList.add(voObj);

        }

        System.out.println("1111"+voList.size());

        return voList;

    }

调用

       List<DeptVO> voList=Util.copyList(poList, DeptVO.class);