当前位置:网站首页>[recommend an entity class conversion tool mapstruct, which is powerful and easy to use]
[recommend an entity class conversion tool mapstruct, which is powerful and easy to use]
2022-06-26 07:12:00 【Java enthusiast】
1. What is? MapStruct
1.1 JavaBean Trouble
For code JavaBean Conversion between , It's been bothering me for a long time . When I was developing, I saw a lot of business code JavaBean Mutual transformation between , Very influential perception , But it has to exist . One way I thought about it later was through reflection , Or write a lot of converters .
The first method of reflection is really convenient , But now whether it's BeanUtils, BeanCopier When using reflection, it will affect the performance . Although we can cache reflection information to improve performance . But words like this , You need the same type and name to map , A lot of times , Because different teams use different terms , Still need a lot of manual set/get And so on .
The second is that it will be a waste of time , And when you add new fields, you also need to modify the methods . however , Because there's no need to reflect , Its performance is very high . recommend :Java Advanced video resources
1.2 MapStruct Change
MapSturct It's a generation type security , High performance and independent JavaBean The annotation processor that maps the code (annotation processor).
- Annotation processor
- Can generate JavaBean The mapping code between
- Type safety , High performance , No dependency
2.MapStruct introduction
2.1 Add dependency

2.2 po class

2.3 dto class

2.4 Create adapters

2.5 The test method

2.6 Running effect

2.7 View compiled class
The bottom layer is completed by automatic value assignment

3.MapStruct Advantage analysis
3.1 High performance
This is relative to reflection , Reflection needs to read bytecode content , It will cost a lot . And by MapStruct To generate code , It's similar to hand writing . Speed can be guaranteed .
3.2 Easy to use
If it's completely mapped , It's certainly not as easy to use as reflection . Use similar BeanUtils These tools are done in one sentence . however , If a special match is needed ( Special type conversion , Many to one conversion, etc ), It's relatively simple .
Basically , When you use it , We just need to declare an interface , Write the corresponding method under the interface , You can use it . Of course , If there are special circumstances , It's something that needs extra treatment . recommend :Java Advanced video resources
3.3 Code independent
The generated code is opposite , No runtime dependencies .
3.4 Easy to debug
In the code we generated , We can do it easily debug.
4.MapStruct Use cases
4.1 Property names are the same
When implementing a class , If the attribute names are the same , The corresponding transformation will be carried out . In this way , We can quickly write the transformation method .( Introductory cases )
4.2 Property names are different
Property names are different , When it's time for mutual transformation , Then we can go through @Mapping Annotation to translate .



- source Docking that needs to be converted , It's usually a reference
- target Butt joint of conversion , Usually out of reference
- ignore Ignore , Default false Don't ignore , It needs to be ignored and set to true
- defaultValue The default value is
- expressions Some simple transformation relations can be constructed through expressions . Although the design wants to be compatible with many languages , But at present, it can only write Java Code .
@Mappings({
@Mapping(source = "birthdate", target = "birth"),// Inconsistent attribute name mapping
@Mapping(target = "birthformat", expression = "java(org.apache.commons.lang3.time.DateFormatUtils.format(person.getBirthdate(),\"yyyy-MM-dd HH:mm:ss\"))"),// Custom attributes can be accessed through java Code mapping
})
public PersonVo PersonToPersonVo(Person person);
Here is a demonstration of how to use TimeAndFormat Yes time and format operation , Here you must specify what you want to use Java The full package name of the class , Otherwise, I don't know which one you use when compiling Java class , Will report a mistake .


4.3 Convert non base type properties
If subUser And subUserDto If the field name is the same, you can configure it directly ( object type , Include list)



4.4 Mapper Use custom transformation in
occasionally , For some types , It can't be handled in the form of a code generator . that , You need a custom method to transform . Now , We can be at the interface ( Same interface , There are other calls in the future Mapper Methods ) The default method is defined in (Java8 And after ).



There can only be one default The method of decoration


4.5 One more turn
We need to transform multiple objects into one scene in the actual business .MapStruct Of course, it also supports the operation of "multi to one" . recommend :Java Advanced video resources





4.5.1 Follow the principles
- When more than one object , One of them is null, Will return directly to null
- Like a one-to-one conversion , Property automatically matches by name . therefore , Those with the same name and type do not need special treatment
- When there are more than one original object , When there is an attribute with the same name , Need to pass through @Mapping Note to specify , To avoid ambiguity ( No error will be reported ). As above name
Properties can also be assigned directly from the parameters passed in

4.6 to update Bean object
occasionally , We don't want to go back to a new Bean object , Instead, I want to update some properties of the incoming object . This is often used in practice .


4.7 map mapping


4.8 Multi level nesting
Only need mapper You can define relevant type conversion methods in the interface ,list Type also applies
4.8.1 The way 1



4.8.2 The way 2
adopt uses Configure type conversion


5. obtain mapper
5.1 adopt Mapper The factory gets
We all passed Mappers.getMapper(xxx.class) In a way that corresponds to Mapper Acquisition . This method is through Mapper The factory gets .
If this is the way , The Convention is to define an instance of the interface itself within the interface INSTANCE, In order to obtain the corresponding instance conveniently .

So when it's called , We don't need to instantiate objects repeatedly . It's like this
Target target = SourceMapper.INSTANCE.source2target(source);5.2 Use dependency injection
about Web Development , Dependency injection should be familiar .MapSturct It also supports the use of dependency injection , It is also recommended to use dependency injection .

@Mapper(componentModel = "spring")5.3 Dependency injection strategy
You can choose to inject... By constructing methods or attributes , The default is property injection .

Use like this
@Mapper(componentModel = "cdi" injectionStrategy = InjectionStrategy.CONSTRUCTOR)5.4 Custom type conversion
occasionally , There may be such a problem in object transformation , The type in the source object is Boolean type , And the target object type is String type , This can be done by @Mapper Of uses Property to implement :




It should be noted that , If you use something like spring Such an environment ,Mapper introduce uses Class instances will be automatically injected , So this class should also be included in Spring Containers

边栏推荐
- How can I find the completely deleted photos in Apple mobile phone?
- 【图像增强】基于人工多重曝光融合AMEF实现图像去雾附matlab代码
- China's Ni MH battery industry development overview analysis and investment trend forecast report 2022 Edition
- Redis系列——redis启动,客户端day1-2
- Young man, do you know the original appearance of kotlin association process?
- Ppbpi-h-cr, ppbpimn Cr, ppbpi Fe Cr alkynyl crosslinked porphyrin based polyimide material Qiyue porphyrin reagent
- 3,3 '- di (3,4-dicarboxyphenoxy) -4,4' - diphenylethynylbiphenyldianhydride (bpebpda) / porphyrin 2dcofs (H2P COF, ZNP COF and cup COF) supplied by Qiyue
- 【图像检测】基于形态学实现图像目标尺寸测量系统附matlab代码
- Liquid crystal texture diagram of purple solid mm-tpp-10c methacrylic acid decanoxy tetraphenyl porphyrin and mm-tpp-12c methacrylic acid dodecanoxy tetraphenyl porphyrin - Qi Yue display
- Deep exploration image theme color extraction
猜你喜欢

【图像检测】基于形态学实现图像目标尺寸测量系统附matlab代码

一文分析EventBus-事件总线的使用方法和实现原理
![[yolov4] matlab simulation of network target detection based on yolov4 deep learning](/img/f9/31aba8f8bc04ccb16486dc87712ef6.png)
[yolov4] matlab simulation of network target detection based on yolov4 deep learning
![Meso tetra (4-bromophenyl) porphyrin (tbpp); 5,10,15,20-tetra (4-methoxy-3-sulfonylphenyl) porphyrin [t (4-mop) ps4] supplied by Qiyue](/img/83/ddbf296ac83f006f31cfd0bbbabe5e.jpg)
Meso tetra (4-bromophenyl) porphyrin (tbpp); 5,10,15,20-tetra (4-methoxy-3-sulfonylphenyl) porphyrin [t (4-mop) ps4] supplied by Qiyue

【图像分割】基于最大主曲率实现视网膜眼底图像中的血管提取附matlab代码

Redis系列——redis启动,客户端day1-2
![[image fusion] MRI-CT image fusion based on gradient energy, local energy and PCA fusion rules with matlab code](/img/fc/fd81dedaa6b7c7542f9d74b04f247c.png)
[image fusion] MRI-CT image fusion based on gradient energy, local energy and PCA fusion rules with matlab code

Analyze 5 indicators of NFT project

【图像融合】基于梯度能量、局部能量、 PCA三种融合规则实现MRI-CT图像融合附matlab代码

This paper analyzes the use method and implementation principle of eventbus event bus
随机推荐
Professional course - Code question record
一项听起来大胆,并且非常牛逼的操作——复刻一个 Netflix
Deep exploration image theme color extraction
Thymeleaf中使用二维数组[[]]报错:Could not parse as expression
C implementation adds a progress bar display effect to the specified column of the GridView table in devaxpress - code implementation method
Calculate division in Oracle - solve the error report when the divisor is zero
Market survey of China's coal to liquid industry and analysis report on investment competitiveness during the "14th five year plan" 2022-2027
【图像检测】基于Itti模型实现图像显著性检测附matlab代码
[image enhancement] image defogging based on artificial multiple exposure fusion amef with matlab code
【推荐10个 让你轻松的 IDEA 插件,少些繁琐又重复的代码】
This paper analyzes the use method and implementation principle of eventbus event bus
面试被问Redis主从复制不会答?这13张图让你彻底弄明白
How to convert Unicode into Chinese characters in Excel
es 中 mapping 简介
【特征提取】基于稀疏PCA实现目标识别信息特征选择附matlab源码
oracle创建带返回值的存储过程并sql执行调用
. Net 20th anniversary! Microsoft sends a document to celebrate
专业课-代码题记录
SQL
Shell input validation alphanumeric only