Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is MapStruct's elegant object transformation solution?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

MapStruct elegant object conversion solution is what kind of, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

When I first saw MapStruct, I was very happy personally. Because it coincides with what I think in my heart.

What is 1 MapStruct? 1.1 troubles of JavaBean

The conversion between JavaBean in the code has been bothering me for a long time.

During the development, I saw that there are a lot of JavaBean transformations between business codes, which have a great impact on the look and feel, but have to exist. One of the ways I came up with later was to use reflection, or write a lot of converters myself.

The first way to use reflection is really convenient, but now both BeanUtils, BeanCopier and so on will affect performance when using reflection. Although we can cache reflection information to improve performance.

But like this, you need the same type and name to map, and in many cases, because different teams use different nouns, you still need a lot of manual set/get and other features.

The second is that it is a waste of time, and the method has to be modified when adding new fields. However, because there is no need for reflection, its performance is very high.

1.2 changes brought about by MapStruct

MapSturct is an annotation processor (annotation processor) that generates type-safe, high-performance and independent JavaBean mapping code.

Focus on the main points:

Annotation processor

You can generate the mapping code between JavaBean

Type safety, high performance, no dependency

From the literal understanding, we can know that this tool can help us achieve the conversion between JavaBean, through the way of annotations.

At the same time, as a tool class, compared with handwriting, it should be convenient and not easy to make mistakes.

2 getting started with MapStruct

Getting started is easy. I manage the jar package of the project based on Maven.

2.1 introduce dependency 1.3.0.Final org.mapstruct mapstruct-jdk8 ${org.mapstruct.version} org.mapstruct mapstruct-processor ${org.mapstruct.version} 2.2 to create entity and dto objects

This class is the part taken down from an order system in github.

Datapublic class Order {/ * order id * / private Long id; / * * order No. * / private String orderSn; / * consignee name / number * / private String receiverKeyword; / * order status: 0-> to be paid; 1-> to be shipped; 2-> shipped; 3-> completed; 4-> closed 5-> invalid order * / private Integer status; / * * order type: 0-> normal order; 1-> second kill order * / private Integer orderType; / * * order source: 0-> PC order; 1-> app order * / private Integer sourceType;}

Corresponding query parameters

@ Datapublic class OrderQueryParam {/ * * order No. * / private String orderSn; / * consignee name / number * / private String receiverKeyword; / * order status: 0-> to be paid; 1-> to be shipped; 2-> shipped; 3-> completed; 4-> closed 5-> invalid order * / private Integer status; / * * order type: 0-> normal order; 1-> second kill order * / private Integer orderType; / * * order source: 0-> PC order; 1-> app order * / private Integer sourceType;} 2.3 write Mapper

Mapper is the mapper, which generally means writing the xxxMapper interface.

Of course, it doesn't have to end in Mapper. It's just that's what the authorities say. In this getting started example, the corresponding interface is as follows

Import com.homejim.mapstruct.dto.OrderQueryParam;import com.homejim.mapstruct.entity.Order;import org.mapstruct.Mapper;import org.mapstruct.Mapping;@Mapperpublic interface OrderMapper {OrderQueryParam entity2queryParam (Order order);}

For a simple mapping (fields and types match), there is only one requirement, just write the @ Mapper annotation on the interface.

Then in the method, the input parameter corresponds to the object to be converted, the return value corresponds to the converted object, and the method name can be arbitrary.

2.4 Test

Write a test class to test it.

@ Testpublic void entity2queryParam () {Order order = new Order (); order.setId (12345L); order.setOrderSn ("orderSn"); order.setOrderType (0); order.setReceiverKeyword ("keyword"); order.setSourceType (1); order.setStatus (2); OrderMapper mapper = Mappers.getMapper (OrderMapper.class); OrderQueryParam orderQueryParam = mapper.entity2queryParam (order); assertEquals (orderQueryParam.getOrderSn (), order.getOrderSn ()) AssertEquals (orderQueryParam.getOrderType (), order.getOrderType ()); assertEquals (orderQueryParam.getReceiverKeyword (), order.getReceiverKeyword ()); assertEquals (orderQueryParam.getSourceType (), order.getSourceType ()); assertEquals (orderQueryParam.getStatus (), order.getStatus ());}

The test passed without any problems.

3 MapStruct analysis

Above, I wrote three steps to implement the conversion from Order to OrderQueryParam.

So what are the advantages of code generated through MapStruct as an annotation processor?

3.1 High performance

This is relative to reflection, which needs to read the contents of the bytecode, which will be more expensive. Learn reflection to read "Java reflection will definitely read this article" this is enough! Follow the official account Java technology stack to read more Java technology practical information tutorials.

The code generated by MapStruct is similar to human handwriting. Speed can be guaranteed.

The code generated in the previous example can be seen after compilation. You can see it in target/generated-sources/annotations.

Generated code

Corresponding code

Generated (value = "org.mapstruct.ap.MappingProcessor", date = "2019-08-02T00:29:49+0800", comments = "version: 1.3.0.Final, compiler: javac, environment: Java 11.0.2 (Oracle Corporation)") public class OrderMapperImpl implements OrderMapper {@ Override public OrderQueryParam entity2queryParam (Order order) {if (order = = null) {return null;} OrderQueryParam orderQueryParam = new OrderQueryParam () OrderQueryParam.setOrderSn (order.getOrderSn ()); orderQueryParam.setReceiverKeyword (order.getReceiverKeyword ()); orderQueryParam.setStatus (order.getStatus ()); orderQueryParam.setOrderType (order.getOrderType ()); orderQueryParam.setSourceType (order.getSourceType ()); return orderQueryParam;}}

You can see that it generates an implementation class, and the code is similar to our handwritten, easy to understand.

3.2 easy to debug

In the code we generate, we can easily do debug.

Easy to DEBUG

When using reflection, if there is a problem, it is often difficult to find out what the cause is.

3.3 it is relatively easy to use

If it is fully mapped, it is certainly not as easy to use as reflection. You can do it with a single sentence with tools like BeanUtils. However, if special matching is needed (special type conversion, many-to-one conversion, etc.), it is also relatively simple.

Basically, when using it, we only need to declare an interface, write the corresponding method under the interface, and we can use it. Of course, if there are special circumstances, additional treatment is required.

3.4 Code Independence

The generated code is opposing and has no runtime dependencies.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report