使用orika进行对象间Mapping
1. 当两个类的属性名都一样
package com.orika;
/**
* Title:CopiedStudent.java
* Description:
*
* @author zhuyang
* @version 1.0 2017/7/18
*/
public class CopiedStudent {
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 "CopiedStudent{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.orika;
/**
* Title:Student.java
* Description:
*
* @author zhuyang
* @version 1.0 2017/7/18
*/
public class Student {
private Integer age;
private String name;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* copy object which filed name is totally same
* @param stu source student
*/
public static void map1(Student stu){
//since filed name is same, so no need to register
MapperFactory factory = new DefaultMapperFactory.Builder().build();
CopiedStudent cs = factory.getMapperFacade(Student.class,CopiedStudent.class).map(stu);
System.out.println("map1==="+cs);
}
2.两个类的字段名不一样
package com.orika;
/**
* Title:CopiedStudent2.java
* Description:
*
* @author zhuyang
* @version 1.0 2017/7/18
*/
public class CopiedStudent2 {
private String name;
private Integer copyAge;
@Override
public String toString() {
return "CopiedStudent2{" +
"name='" + name + '\'' +
", copyAge=" + copyAge +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCopyAge() {
return copyAge;
}
public void setCopyAge(Integer copyAge) {
this.copyAge = copyAge;
}
}
/**
* copy object which filed name is different
* @param stu
*/
public static void map2(Student stu){
MapperFactory factory = new DefaultMapperFactory.Builder().build();
//since filed name is not same, so register is required
ClassMapBuilder builder = factory.classMap(Student.class,CopiedStudent2.class);
builder.field("age","copyAge");
builder.byDefault().register();
CopiedStudent2 cs2 = factory.getMapperFacade().map(stu,CopiedStudent2.class);
System.out.println("map2==="+cs2);
}
3. List拷贝
public static void mapAsList(List<Student> studens){
//register copiedStudent2, since Student and CopiedStudent2 are using different filed name, so register is required.
MapperFactory factory = new DefaultMapperFactory.Builder().build();
ClassMapBuilder builder = factory.classMap(Student.class,CopiedStudent2.class);
builder.field("age","copyAge");// map field
builder.byDefault().register();
List<CopiedStudent2> copiedStudent2s = factory.getMapperFacade().mapAsList(studens,CopiedStudent2.class);
copiedStudent2s.forEach(student ->{
System.out.println("copiedStuden2 list = "+student);
});
}