Explanation of Java Entity Mapping Tool MapStruct

  • 2021-12-11 07:40:18
  • OfStack

Directory 1. Order 2. Simple use cases 3. Use a detailed explanation 1) Detailed explanation of the usage of several attributes of interface annotation @ Mapper
2) Other method-level comments
Summarize

1. Order

Usually, in the back-end development, the entity Entity class is often not directly returned, and it is returned to the front end after processing and conversion. The objects submitted by the front end also need to be converted into Entity entities before storage; The commonly used BeanUtils. copyProperties method is also rough, not only inefficient (using reflection), but also only maps attributes with the same name. In most cases, the corresponding transformation method implementation needs to be written manually.

The plug-in MapStruct gracefully implements object transformation with interface method and annotation, the MapStruct generator generates code closer to the native Setter, and the Getter method handles attribute mapping more efficiently.

https://github.com/mapstruct/mapstruct/

https://github.com/mapstruct/mapstruct-examples

2. Simple use cases

Entity Object User


@Data
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;
    private String address;
}

Transform object UserVO


@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}

Conversion interface


@Test
public void contextLoads() {
    User user = new User(0, "Tester", 1, " Xuhui District, Shanghai ");
    UserVO userVO = UserConvert.INSTANCE.toVO(user);
}

Use sample


@Test
public void contextLoads() {
    User user = new User(0, "Tester", 1, " Xuhui District, Shanghai ");
    UserVO userVO = UserConvert.INSTANCE.toVO(user);
}

3. Use a detailed explanation

1) Detailed explanation of the usage of several attributes of interface annotation @ Mapper

uses uses other manually written or other Mapper interface overrides related transformation methods and cannot be referenced cyclically


@Mapper(uses=DateMapper.class)

imports refers to related classes, allowing these types to be used directly through mapping. expression (), mapping. defaultExpression ()


@Mapper(imports = DateUtil.class)
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mappings({
            @Mapping(source = "name", target = "userName"),
            //  Convert properties with the specified method, if you don't use the imports You need to write the full reference class package path 
            @Mapping(target = "birthday", expression = "java(DateUtil.formatDate(entity.getBirthday()))")
    })
    UserVO toVO(User entity);
}

unmappedSourcePolicy, unmappedTargetPolicy Feedback Policy for Unmapped Attributes in Source Type/Target Type

typeConversionPolicy feedback strategy for lossy conversion, such as Long to Integer

There are three main feedback strategies: IGNORE, default value, and ignoring unmapped fields. WARN, warning. ERROR, error report


@Mapper(unmappedSourcePolicy = ReportingPolicy.ERROR)

componentModel specifies four main modes for generating mapper instances:

default, which does not actively generate instances, is typically instantiated as Mappers. getMapper (Class).

cdi, instantiates the mapper with the CDI standard, injects related instances with @ Inject,

spring, Spring Bean mode instantiation,

jsr330, jsr330 Standard Instantiation


@Mapper(componentModel = "spring")
public interface UserConvert {
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}

@Autowired
private UserConvert userConvert;

implementationName specifies the implementation class name, and the mapping generator interface automatically generates the implementation class < CLASS_NAME > Impl, use this property to avoid class conflicts

implementationPackage specifies the implementation class package path

config specifies the configuration class, and the associated configuration is imported by the specified @ MapperConfig configuration class, config

Configuration class


@MapperConfig(
        uses = DateUtil.class,
        unmappedSourcePolicy = ReportingPolicy.WARN
)
public interface UserConfig {
}

Import configuration class


@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}
0

collectionMappingStrategy collection mapping strategy. When paying attention to collection mapping, if the type in the collection has a corresponding conversion method, it will be used first when converting the collection


@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}
1

GENERATED CODE Generator Generates Code


@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}
2

nullValueMappingStrategy null as the source value mapping strategy; RETURN_NULL returns null by default, RETURN_DEFAULT returns the default value, the object is automatically constructed by the constructor, and the collection returns an empty collection

When the value is RETURN_DEFAULT, if Mapping. expression and Mapping. constant are included in the mapping rule, it must be judged null manually, otherwise NPE


@MapperConfig(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)

NullValuePropertyMappingStrategy null as the source attribute mapping strategy; SET_TO_NULL returns null by default, SET_TO_DEFAULT returns the default value, and IGNORE ignores this value based on the existing value of the target object

MappingInheritanceStrategy inherits the method level mapping configuration policy: EXPLICIT shows that InheritConfiguration is effective.

AUTO_INHERIT_FROM_CONFIG automatically inherits the configuration of the forward transformation. AUTO_INHERIT_REVERSE_FROM_CONFIG automatically inherits the configuration of the reverse transformation. AUTO_INHERIT_ALL_FROM_CONFIG inherits


@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}
4

@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}
5

nullValueCheckStrategy null value monitoring strategy

2) Other method-level comments

@ InheritInverseConfiguration Inheritance Mapping Rules on Reverse Conversion

Mapping rules for @ Mapping configuration type attributes;

dateFormat Formatted Date


@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}
6

numberFormat Digital Formatting


@Mapper
public interface UserConvert {
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    @Mapping(source = "name", target = "userName")
    UserVO toVO(User entity);
}
7

constant Constant


@Mapping(target = "age", constant = "0")

Summarize


Related articles: