orika core工具对实体(Bean)进行深度拷贝
Posted miaoying
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了orika core工具对实体(Bean)进行深度拷贝相关的知识,希望对你有一定的参考价值。
在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)进行深度拷贝的主要内容,如果未能解决你的问题,请参考以下文章