Using @Mapping annotation, we can define the mappings between to classes.
For example,
User.java
public class User {
private Integer id;
private String fName;
private String lName;
......
......
}
Student.java
public class Student {
private Integer id;
@Mapping("fName")
private String firstName;
@Mapping("lName")
private String lastName;
.......
.......
}
As you see above snippet, I specified the mappings using @Mapping annotation (this mapping is bi-directional).
a. fName should be mapped to firstName
b. lName should be mapped to lastName
Find the below working application.
User.java
package com.sample.app.model;
public class User {
private Integer id;
private String fName;
private String lName;
public User() {
}
public User(Integer id, String fName, String lName) {
this.id = id;
this.fName = fName;
this.lName = lName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
@Override
public String toString() {
return "User [id=" + id + ", fName=" + fName + ", lName=" + lName + "]";
}
}
Student.java
package com.sample.app.model;
import org.dozer.Mapping;
public class Student {
private Integer id;
@Mapping("fName")
private String firstName;
@Mapping("lName")
private String lastName;
public Student() {
}
public Student(Integer id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
CustomMappingWithAnnotations.java
package com.sample.app;
import java.io.IOException;
import org.dozer.DozerBeanMapper;
import com.sample.app.model.Student;
import com.sample.app.model.User;
public class CustomMappingWithAnnotations {
public static void main(String[] args) throws IOException {
DozerBeanMapper mapper = new DozerBeanMapper();
User user1 = new User(1, "Arjun", "Gurram");
Student student1 = mapper.map(user1, Student.class);
User user2 = mapper.map(student1, User.class);
System.out.println(user1);
System.out.println(student1);
System.out.println(user2);
}
}
Output
User [id=1, fName=Arjun, lName=Gurram] Student [id=1, firstName=Arjun, lastName=Gurram] User [id=1, fName=Arjun, lName=Gurram]
Previous Next Home
No comments:
Post a Comment