Method for MapStruct to Deal with Unmatched Attribute Conversion between Entity and Model in Java

  • 2021-07-06 10:56:37
  • OfStack

Summary: The simple usage of MapStrut was introduced earlier, and the most important feature of MapStrut is to deal with the transformation of mismatched attributes between entities and models in Java.

Solid model

There is 1 User object:


public class User {
  private Integer id;
  private String name;
  private double account;
  private boolean married;
// setters, getters, toString()
}

There is 1 Employee object:


public class Employee {
  private int id;
  private String ename;
  private String position;
  private String married;
// setters, getters, toString()
}

Business scenario

A conversion between User and Employee objects is required. The name attribute of User corresponds to the ename attribute of Employee, with the same value, same type and different name The married attribute of User (values true and false) corresponds to the married attribute of Employee (values Y and N), with different values, different types and the same name.

Analysis and Implementation

The stupidest way is to write a pile of setter methods and getter methods by yourself, and a large number of get/set codes are piled up, which increases the code length and the difficulty of reading the code. You can handle the first requirement with the tool BeanUtils, but you can't handle the third requirement. At this time, MapStrut comes in handy, and the simplest configuration can look like the following:


@Mapper
public interface UserMapper {
  UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
  Employee userToEmployee(User user);
  User employeeToUser(Employee employee);
}

For the second requirement, it can be realized in the following ways, annotation @Mapping You can specify which field you want to put source Which field to convert to target .


@Mapper
public interface UserMapper {
  UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
  @Mappings({
    @Mapping(source="name", target="ename")
  })
  Employee userToEmployee(User user);
  @Mappings({
    @Mapping(source="ename", target="name")
  })
  User employeeToUser(Employee employee);
}

The third requirement is a bit abnormal, but it really happens in our project, and it is really cumbersome to implement:

First, customize the conversion logic, Boolean value to string, Boolean true corresponding to string Y, Boolean false corresponding to string N:


public class UserTransform {
  public String booleanToString(boolean value){
    if(value){
      return "Y";
    }
    return "N";
  }
  public boolean strToBoolean(String str){
    if ("Y".equals(str)) {
      return true;
    }
    return false;
  }
}

It is very simple to use, and it is added in the annotation Mapper of the interface uses Parameters and values are the conversion logic classes that need just now.


@Mapper(uses = UserTransform.class)
public interface UserMapper {...}

Results and analysis

Junit Test is used to write two test methods to test User object conversion Employee and Employee object conversion User respectively.


public class MidTest {
  @Test
  public void midTest(){
    User user = new User();
    user.setId(125);
    user.setName("Lee");
    user.setMarried(true);
    Employee e = UserMapper.INSTANCE.userToEmployee(user);
    System.out.println(e);
  }
  @Test
  public void midTest2(){
    Employee e = new Employee();
    e.setId(222);
    e.setEname("Chao");
    e.setMarried("N");
    User u = UserMapper.INSTANCE.employeeToUser(e);
    System.out.println(u);
  }
}

The results are as follows:

User [id=222, name=Chao, account=0.0, married=false]
Employee [id=125, ename=Lee, position=null, married=Y]

The conversion results are expected, and attributes that do not exist during the conversion have default values (account and position), and the wrapper class can also recognize (int and Integer) from the automatically generated UserMapperImpl.java As you can see,

employee.setMarried( userTransform.booleanToString( user.isMarried() ) ); Using the transformation logic just customized. The third requirement is very few, but it is difficult to solve when it comes to it. The custom function of MapStruct is really convenient, but compared with other conversion tools, it is really difficult to get started and the configuration is slightly cumbersome.

Project code is hosted in the code cloud.

Summarize


Related articles: