当前位置:网站首页>[detailed] several ways to quickly realize object mapping
[detailed] several ways to quickly realize object mapping
2022-07-06 01:24:00 【A rookie is a great God】
Project development process , Often need to write model Conversion between , The most common ones are :
- Entity transfer DTO
- DTO Transfer to entity
- …
for instance :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Entity :User @Data @Builder @NoArgsConstructor @AllArgsConstructor public class User { private Integer id; private String email; private String username; private String password; private Integer gender; private Date birthday; } // DTO:UserRegisterReq @Data public class UserRegisterReq { private String username; private String password; private String confirmPassword; private String email; } |
among :
- UserRegisterReq When the user registers ,Controller Request input of layer
- User Is a user entity
When performing registration , We need to UserRegisterReq convert to User object , Then store it in the database . here , We often write code similar to the following :
1 2 3 4 5 6 7 8 9 | @PostMapping("/users/reg") public void reg(@RequestBody UserRegisterReq userRegisterReq) { // Omit password And confirmPassword Equivalent judgment User user = new User(); user.setEmail(userRegisterReq.getEmail()); user.setPassword(userRegisterReq.getPassword()); user.setUsername(userRegisterReq.getUsername()); // preservation user... } |
Although the above code is feasible , But if the class field A lot , Then it will be more troublesome —— We wrote a lot of code , It's just to realize the conversion of objects .
Method 1 、IDEA Plug in fast conversion
IDEA Provide GenerateAllSetter plug-in unit , It can help us generate the above code quickly .
- Plug in home page :GenerateAllSetter - IntelliJ IDEs Plugin | Marketplace
- GitHub:GitHub - gejun123456/intellij-generateAllSetMethod: Intellij plugin to generate call to setter method value for class
The demonstration is shown in the following figure :
Just install the plug-in , Then press Alt + Enter(macOS It is Option + Enter), Object conversion code can be generated automatically .
Method 2 、 Realize object transformation with the help of object mapping framework
Method one is very convenient , But if the object has many fields , Then the code will still be very verbose , It's not simple enough .
in fact ,Java Ecology has many object mapping frameworks , It specially helps us realize the conversion between objects . Here the author lists the options commonly used in the industry :
product | Dozer | Orika | MapStruct | CGLib BeanCopier | Spring BeanUtils | Apache BeanUtils |
---|---|---|---|---|---|---|
GitHub | dozer 1.9K stars | orika 1.2K stars | mapstruct 5K stars | cglib 4.3K stars | - | commons-beanutils 0.2K stars |
working principle | A lot of reflection , Based mainly on Field.set(obj, obj) by field assignment | be based on javassist Generate object mapping bytecode , And load the generated bytecode file | be based on JSR269, Generate object mapping code at compile time | be based on ASM Of MethodVisitor by field assignment | be based on Spring Reflection tools | Based on reflection |
Performance ranking | 5 | 2 | 1 | 4 | 3 | 6 |
Although there are many options , But the author only suggests that you use MapStruct.
MapStruct advantage :
- Compiler generation Getter/Setter, No performance loss during operation , Strong performance
- be based on JSR269, Flexible configuration
- be based on Getter/Setter, And write by yourself Getter/Setter There is no difference between , It is more convenient to search for field references
shortcoming :
- Due to the flexible configuration , So the starting cost is a little higher than other components
MapStruct Get started
To configure IDE
Reference resources IDE Support – MapStruct , Configure your IDE
Integrate
Add the following to the project :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
<!-- ref: https://mapstruct.org/documentation/installation/ --> <properties> <org.mapstruct.version>1.4.2.Final</org.mapstruct.version> </properties> ... <dependencies> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>${org.mapstruct.version}</version> </dependency> </dependencies> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <!-- depending on your project --> <target>1.8</target> <!-- depending on your project --> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> <!-- other annotation processors --> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
If your project uses Lombok, Or use spring-boot-configuration-processor, Then use a configuration similar to the following :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
<properties> <org.mapstruct.version>1.4.2.Final</org.mapstruct.version> </properties> ... <dependencies> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>${org.mapstruct.version}</version> </dependency> </dependencies> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>8</source> <target>8</target> <encoding>UTF-8</encoding> <!-- https://mapstruct.org/documentation/installation/ --> <!-- https://mapstruct.org/documentation/stable/reference/html/#lombok --> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </path> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok-mapstruct-binding</artifactId> <version>0.1.0</version> </path> <path> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>2.4.1</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
Use
Defining interfaces , The code is similar to :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import com.itmuch.gogolive1.domain.User; import com.itmuch.gogolive1.domain.UserRegisterReq; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper public interface UserConverter { /** * Fixed writing :Mappers.getMapper( The interface name .class); */ UserConverter INSTANCE = Mappers.getMapper(UserConverter.class); User toUser(UserRegisterReq req); }
Use :
1 2 3 4 5 6
@PostMapping("/users/reg") public void reg2(@RequestBody UserRegisterReq userRegisterReq) { // Omit password And confirmPassword Equivalent judgment User user = UserConverter.INSTANCE.toUser(userRegisterReq); // preservation user... }
From the code , Just use the following code , Can be UserRegisterReq transformation User.
1
User user = UserConverter.INSTANCE.toUser(userRegisterReq);
principle
Compile code , And in front UserConverter On the interface , Press shortcut key Command + Option + B
( Or click on Navigate - Implementation(s)
) , lookup UserConverter Implementation class of , You can jump to the following code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2022-03-22T00:29:49+0800", comments = "version: 1.4.2.Final, compiler: javac, environment: Java 11.0.9.1 (Azul Systems, Inc.)" ) public class UserConverterImpl implements UserConverter { @Override public User toUser(UserRegisterReq req) { if ( req == null ) { return null; } UserBuilder user = User.builder(); user.email( req.getEmail() ); user.username( req.getUsername() ); user.password( req.getPassword() ); return user.build(); } } |
From the code ,MapStruct During compilation , Generated UserConverterImpl, And realize the conversion between objects .
and Spring Integrate
MapStruct Support and Spring Integrate , Just follow the steps below :
To write Mapper Interface , And add
(componentModel = "spring")
attribute :1 2 3 4
@Mapper(componentModel = "spring") public interface UserSpringConverter { User toUser(UserRegisterReq req); }
When used , Just inject
UserSpringConverter
that will do :1 2
@Autowired UserSpringConverter userSpringConverter;
This is because , Use
(componentModel = "spring")
after , The generated implementation class will be automatically added@Component
annotation
expand
This article only introduces a relatively simple example , in fact ,MapStruct Support very flexible configuration , for example :
Enumeration mapping
1 2 3 4 5 6 7 8 9 10 11 12
@Mapper public interface OrderMapper { OrderMapper INSTANCE = Mappers.getMapper( OrderMapper.class ); @ValueMappings({ @ValueMapping(target = "SPECIAL", source = "EXTRA"), @ValueMapping(target = "DEFAULT", source = "STANDARD"), @ValueMapping(target = "DEFAULT", source = "NORMAL") }) ExternalOrderType orderTypeToExternalOrderType(OrderType orderType); }
Custom expression mapping :
1 2 3 4 5 6 7 8
@Mapper public interface SourceTargetMapper { SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class ); @Mapping(target = "timeAndFormat", expression = "java( new org.sample.TimeAndFormat( s.getTime(), s.getFormat() ) )") Target sourceToTarget(Source s); }
边栏推荐
- Superfluid_ HQ hacked analysis
- 2022年广西自治区中职组“网络空间安全”赛题及赛题解析(超详细)
- Leetcode sword finger offer 59 - ii Maximum value of queue
- 在产业互联网时代,将会凭借大的产业范畴,实现足够多的发展
- Format code_ What does formatting code mean
- Pbootcms plug-in automatically collects fake original free plug-ins
- Use of crawler manual 02 requests
- Electrical data | IEEE118 (including wind and solar energy)
- 测试/开发程序员的成长路线,全局思考问题的问题......
- After 95, the CV engineer posted the payroll and made up this. It's really fragrant
猜你喜欢
SSH login is stuck and disconnected
基于DVWA的文件上传漏洞测试
MATLB|实时机会约束决策及其在电力系统中的应用
伦敦银走势中的假突破
JVM_ 15_ Concepts related to garbage collection
A picture to understand! Why did the school teach you coding but still not
How to see the K-line chart of gold price trend?
A Cooperative Approach to Particle Swarm Optimization
Finding the nearest common ancestor of binary tree by recursion
[技术发展-28]:信息通信网大全、新的技术形态、信息通信行业高质量发展概览
随机推荐
Five challenges of ads-npu chip architecture design
【全网最全】 |MySQL EXPLAIN 完全解读
现货白银的一般操作方法
What is the most suitable book for programmers to engage in open source?
[pat (basic level) practice] - [simple mathematics] 1062 simplest fraction
Four commonly used techniques for anti aliasing
记一个 @nestjs/typeorm^8.1.4 版本不能获取.env选项问题
servlet(1)
MySQL learning notes 2
VMware Tools installation error: unable to automatically install vsock driver
1791. Find the central node of the star diagram / 1790 Can two strings be equal by performing string exchange only once
Leetcode daily question solution: 1189 Maximum number of "balloons"
False breakthroughs in the trend of London Silver
MATLB|实时机会约束决策及其在电力系统中的应用
Introduction to robotics I. spatial transformation (1) posture, transformation
Docker compose配置MySQL并实现远程连接
Loop structure of program (for loop)
Condition and AQS principle
朝招金安全吗 会不会亏损本金
ClickOnce 不支持请求执行级别“requireAdministrator”