码迷,mamicode.com
首页 > 其他好文 > 详细

orika core工具对实体(Bean)进行深度拷贝

时间:2018-10-09 19:07:22      阅读:1900      评论:0      收藏:0      [点我收藏+]

标签:return   getname   over   pid   int   div   tostring   demo   com   

在pom.xml中添加orika core依赖:

 <!-- https://mvnrepository.com/artifact/ma.glasnost.orika/orika-core -->
        <dependency>
            <groupId>ma.glasnost.orika</groupId>
            <artifactId>orika-core</artifactId>
            <version>1.4.1</version>
        </dependency>

User1和User2是两个实体,部分属性一致:

User1.java 如下

public class User1 {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User1{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

User2.java如下:

public class User2 {
    private String name;
    private Integer age;
    private String agent;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAgent() {
        return agent;
    }

    public void setAgent(String agent) {
        this.agent = agent;
    }

    @Override
    public String toString() {
        return "User2{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ", agent=‘" + agent + ‘\‘‘ +
                ‘}‘;
    }
}

使用orika core可以将User1的内容复制到User2

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

public class Demo03 {
    public static void main(String[] args) {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.classMap(User1.class, User2.class)
                .field("name", "name")
                .field("age", "age")
                .byDefault()
                .register();

        User1 user1 = new User1();
        user1.setName("user1");
        user1.setAge(1);

        MapperFacade mapperFacade = mapperFactory.getMapperFacade();
        User2 user2 = mapperFacade.map(user1, User2.class);
        System.out.printf("user2: " + user2.toString());
    }
}

结果:

user2: User2{name=‘user1‘, age=1, agent=‘null‘}

 

orika core工具对实体(Bean)进行深度拷贝

标签:return   getname   over   pid   int   div   tostring   demo   com   

原文地址:https://www.cnblogs.com/miaoying/p/9761999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!