Simple usage of MapStruct inter entity conversion

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

Abstract: In practical projects, we often need to convert PO to DTO, DTO to PO and other entities. The famous ones are BeanUtil and ModelMapper, which are simple to use, but they are not enough in slightly complex business scenarios. MapStruct this plug-in can be used to deal with domin entity class and model class attribute mapping, configurable.

Establish Maven project

MapStruct requires eye-catching build tools such as Maven, and if the project structure is not standard, the corresponding transformation class may not be generated. Here I use Maven to build the project.


<properties>
<org.mapstruct.version>1.2.0.CR1</org.mapstruct.version>
</properties>

MapStruct is a 1 straight in the progress of the tool, after the version of continuous improvement of the previous version of the deficiencies, repair the previous version of bug, the best use of the latest stable version.


<dependencies>
  <dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-jdk8</artifactId>
    <version>${org.mapstruct.version}</version>
  </dependency>
</dependencies>

Need to introduce dependency packages, you can see the use of java8, the latest version has even supported java9. Of course, this does not mean that you have to use java8, and it is OK for java to be higher than java6.


<build>
  <plugins>
    <plugin>
<groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.5.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <annotationProcessorPaths>
          <path>
  <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
        <version>${org.mapstruct.version}</version>
          </path>
        </annotationProcessorPaths>
      </configuration>
    </plugin>
  </plugins>
</build>

The Maven plug-in is essential and the format is fixed.

Simple example

There is 1 entity class-user User


public class User {
  private int id;
  private String name;
  private boolean married;
// setters, getters, toString
}

There is 1 Entity Class-Employee Employee. Employee is also a user, only one more attribute than user-Position position


public class Employee {
  private int id;
  private String name;
  private String position;
  private boolean married;
// setters, getters, toString
}

In specific business scenarios, User objects need to be converted into Employee objects, and sometimes Employee objects need to be converted into User objects.

To use MapStrut, you need to write one interface:


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

Run the sample

First of all, it is necessary mvn compile Automatically generate the conversion code. The generated code is placed in the target/annotations Below. The general code is as follows:


import com.training.mapstrut.model.Employee;
import com.training.mapstrut.model.User;
import javax.annotation.Generated;
@Generated(
  value = "org.mapstruct.ap.MappingProcessor",
  date = "2017-08-26T17:08:23+0800",
  comments = "version: 1.2.0.CR1, compiler: javac, environment: Java 1.8.0_92 (Oracle Corporation)"
)
public class UserMapperImpl implements UserMapper {
  @Override
  public Employee userToEmployee(User user) {
    if ( user == null ) {
      return null;
    }
    Employee employee = new Employee();
    employee.setId( user.getId() );
    employee.setName( user.getName() );
    employee.setMarried( user.isMarried() );
    return employee;
  }
  @Override
  public User employeeToUser(Employee employee) {
    if ( employee == null ) {
      return null;
    }
    User user = new User();
    user.setId( employee.getId() );
    user.setName( employee.getName() );
    user.setMarried( employee.isMarried() );
    return user;
  }
}

Simply write a test class experiment 1.


public class AppTest{
  @Test
  public void appTest(){
    User user = new User();
    user.setId(125);
    user.setName("Chao");
    user.setMarried(false);
    Employee e = UserMapper.INSTANCE.userToEmployee(user);
    System.out.println(e);
    Assert.assertFalse(e.isMarried());
  }
}

Result output:

Employee [id=125, name=Chao, position=null, married=false]

The effect is good, the fields that need to be converted are accurate, but some people want to vomit bad. This usage is much more complicated than BeanUtil, and it only achieves the same effect. This simple transformation really doesn't require MapStruct, but it needs to do more complex business scenarios.

MapStruct problem

1. MapStruct conversion is inaccurate.

MapStruct1 straight in the update, 1 some features in the old version can not be recognized, in the use of the most important use of the newer version.

2. Under Eclipse, the support of M2E plug-in is required. If there is no integration in Eclipse, it is necessary to go to Eclipse Marketplace Sometimes you need to specify the following configuration in the pom.xml properties to enable Annotation Processing
<m2e.apt.activation>jdt_apt</m2e.apt.activation>

3. Under Eclipse, Maven compile prompt Nothing to compile - all classes are up to date You can try 1 and fill it in Golds clean install compile .

4. When compiling Maven, you must use JDK, not JRE, and the version is higher than jdk 6.

5. In Eclipse, make sure * MapperImpl. java has been generated, but the run times an error ClassNotFoundException: Cannot find implementation for com...*Mapper
Right-click on the project > properties > Java Compiler > Annotation Processing (all entries of Enable) > Factory Path (Enable) > Add External JARS > Select mapstruct-processor-*.jar (Probably in the computer directory .m2\repository\org\mapstruct\mapstruct-processor ) > OK

Summarize


Related articles: