DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus
  • Dust Actors and Large Language Models: An Application
  • Five Java Developer Must-Haves for Ultra-Fast Startup Solutions

Trending

  • The Modern Data Stack Is Overrated — Here’s What Works
  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • Understanding Java Signals
  • A Guide to Container Runtimes
  1. DZone
  2. Coding
  3. Java
  4. Introduction to MapStruct: An Easy and Fast Mapping at Compile Time

Introduction to MapStruct: An Easy and Fast Mapping at Compile Time

MapStruct: easy mappings between Java beans

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Sep. 16, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
20.2K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous article, we learned about the proposal of DTO, the benefits and the issues about this new layer in our Java Application We can isolate the model from control in the MVC architecture perspective, although we add a new layer that implies more complexity, furthermore,  there is a work of conversion between entity and DTO. In this tutorial, we'll explore one more tool the MapStruct.

MapStruct is a code generator that dramatically simplifies the mappings between Java bean types based on a convention over configuration approach. The generated mapping code uses explicit method invocations and thus is fast, type-safe, and easy to understand.

To demonstrate how to use this mapper and compare the ModelMapper with MapStruct, we'll rewrite the same application, however, with MapStruct instead. Thus, we'll create a MicroProfile/Jakarta EE application with Payara Micro to store the user information; on this service, we'll store the nickname, salary, languages, birthday, and several settings.

We'll use a maven project, therefore, we need to add the MapStruct in your dependencies as the first step.

XML
 




xxxxxxxxxx
1
36


 
1
<build>
2
        <finalName>microprofile</finalName>
3
        <plugins>
4
            <plugin>
5
                <groupId>org.apache.maven.plugins</groupId>
6
                <artifactId>maven-compiler-plugin</artifactId>
7
                <version>${maven.compile.version}</version>
8
                <configuration>
9
                    <target>${maven.compiler.target}</target>
10
                    <source>${maven.compiler.source}</source>
11
                    <annotationProcessorPaths>
12
                        <path>
13
                            <groupId>org.mapstruct</groupId>
14
                            <artifactId>mapstruct-processor</artifactId>
15
                            <version>${org.mapstruct.version}</version>
16
                        </path>
17
                    </annotationProcessorPaths>
18
                    <compilerArgs>
19
                        <compilerArg>
20
                            -Amapstruct.suppressGeneratorTimestamp=true
21
                        </compilerArg>
22
                        <compilerArg>
23
                            -Amapstruct.suppressGeneratorVersionInfoComment=true
24
                        </compilerArg>
25
                    </compilerArgs>
26
                </configuration>
27
            </plugin>
28
    </build>
29

          
30
    <dependencies>
31
        <dependency>
32
            <groupId>org.mapstruct</groupId>
33
            <artifactId>mapstruct</artifactId>
34
            <version>${org.mapstruct.version}</version>
35
        </dependency>
36
    </dependencies>



In the persistence layer, we'll use MongoDB that is so far the most popular NoSQL database in the globe. To make the communication more natural between Java and the database, we'll use Jakarta NoSQL. We'll define default settings to run locally, but thanks to Eclipse MicroProfile, we can overwrite those on the production environment.

Java
 




xxxxxxxxxx
1
52


 
1
import jakarta.nosql.mapping.Column;
2
import jakarta.nosql.mapping.Convert;
3
import jakarta.nosql.mapping.Entity;
4
import jakarta.nosql.mapping.Id;
5
import my.company.infrastructure.MonetaryAmountAttributeConverter;
6

          
7
import javax.money.MonetaryAmount;
8
import java.time.LocalDate;
9
import java.util.Collections;
10
import java.util.List;
11
import java.util.Map;
12
import java.util.Objects;
13

          
14
@Entity
15
public class User {
16

          
17
    @Id
18
    private String nickname;
19

          
20
    @Column
21
    @Convert(MonetaryAmountAttributeConverter.class)
22
    private MonetaryAmount salary;
23

          
24
    @Column
25
    private List<String> languages;
26

          
27
    @Column
28
    private LocalDate birthday;
29

          
30
    @Column
31
    private Map<String, String> settings;
32

          
33
   //getter and setter
34
}
35

          
36
import java.util.List;
37
import java.util.Map;
38

          
39
public class UserDTO {
40

          
41
    private String nickname;
42

          
43
    private String salary;
44

          
45
    private List<String> languages;
46

          
47
    private String birthday;
48

          
49
    private Map<String, String> settings;
50

          
51
   //getter and setter
52
}



The Magic happens in the interface that has the Mapper annotation, which marks the interface as a mapping interface and lets the MapStruct processor kick in during compilation. We set the component as CDI because we'll make the interface eligible to CDI context injection.

Java
 




xxxxxxxxxx
1
64


 
1
import org.javamoney.moneta.Money;
2
import org.mapstruct.Mapper;
3
import org.mapstruct.Mapping;
4
import org.mapstruct.Named;
5

          
6
import javax.money.MonetaryAmount;
7
import java.time.LocalDate;
8
import java.util.Collections;
9
import java.util.List;
10
import java.util.stream.Collectors;
11

          
12
@Mapper(componentModel = "cdi")
13
public interface UserMapper {
14

          
15
    @Mapping(source = "salary", target = "salary", qualifiedByName = "moneyString")
16
    @Mapping(source = "birthday", target = "birthday", qualifiedByName = "localDateString")
17
    @Mapping(source = "languages", target = "languages", qualifiedByName = "languages")
18
    UserDTO toDTO(User user);
19

          
20
    @Mapping(source = "salary", target = "salary", qualifiedByName = "money")
21
    @Mapping(source = "birthday", target = "birthday", qualifiedByName = "localDate")
22
    @Mapping(source = "languages", target = "languages", qualifiedByName = "languages")
23
    User toEntity(UserDTO dto);
24

          
25
    @Named("money")
26
    static MonetaryAmount money(String money) {
27
        if (money == null) {
28
            return null;
29
        }
30
        return Money.parse(money);
31
    }
32

          
33
    @Named("localDate")
34
    static LocalDate localDate(String date) {
35
        if (date == null) {
36
            return null;
37
        }
38
        return LocalDate.parse(date);
39
    }
40

          
41
    @Named("moneyString")
42
    static String moneyString(MonetaryAmount money) {
43
        if (money == null) {
44
            return null;
45
        }
46
        return money.toString();
47
    }
48

          
49
    @Named("localDateString")
50
    static String localDateString(LocalDate date) {
51
        if (date == null) {
52
            return null;
53
        }
54
        return date.toString();
55
    }
56

          
57
    @Named("languages")
58
    static List<String> convert(List<String> languages) {
59
        if (languages == null) {
60
            return Collections.emptyList();
61
        }
62
        return languages.stream().collect(Collectors.toList());
63
    }
64
}



One of the significant advantages of using Jakarta NoSQL is its ease of integrating the database. For example, in this article, we will use the concept of a repository from which we will create an interface for which Jakarta NoSQL will take care of this implementation.

Java
 




xxxxxxxxxx
1


 
1
import jakarta.nosql.mapping.Repository;
2

          
3
import javax.enterprise.context.ApplicationScoped;
4
import java.util.stream.Stream;
5

          
6
@ApplicationScoped
7
public interface UserRepository extends Repository<User, String> {
8
    Stream<User> findAll();
9
}



In the last step, we will make our appeal with JAX-RS. The critical point is that the data exposure will all be done from the DTO; that is, it is possible to carry out any modification within the entity without the customer knowing, thanks to the DTO. As mentioned, the mapper was injected, and the 'map' method greatly facilitates this integration between the DTO and the entity without much code for that.

Java
 




xxxxxxxxxx
1
55


 
1
import javax.inject.Inject;
2
import javax.ws.rs.*;
3
import javax.ws.rs.core.MediaType;
4
import javax.ws.rs.core.Response;
5
import java.util.List;
6
import java.util.stream.Collectors;
7
import java.util.stream.Stream;
8

          
9
@Path("users")
10
@Consumes(MediaType.APPLICATION_JSON)
11
@Produces(MediaType.APPLICATION_JSON)
12
public class UserResource {
13

          
14
    @Inject
15
    private UserRepository repository;
16

          
17
    @Inject
18
    private UserMapper mapper;
19

          
20
    @GET
21
    public List<UserDTO> getAll() {
22
        Stream<User> users = repository.findAll();
23
        return users.map(mapper::toDTO)
24
                .collect(Collectors.toList());
25
    }
26

          
27
    @GET
28
    @Path("{id}")
29
    public UserDTO findById(@PathParam("id") String id) {
30
        return repository.findById(id)
31
                .map(mapper::toDTO)
32
                .orElseThrow(
33
                        () -> new WebApplicationException(Response.Status.NOT_FOUND));
34
    }
35

          
36
    @POST
37
    public void insert(UserDTO dto) {
38
        User map = mapper.toEntity(dto);
39
        repository.save(map);
40
    }
41

          
42
    @POST
43
    @Path("{id}")
44
    public void update(@PathParam("id") String id, UserDTO dto) {
45
        User user = repository.findById(id).orElseThrow(() ->
46
                new WebApplicationException(Response.Status.NOT_FOUND));
47
        repository.save(mapper.toEntity(dto));
48
    }
49

          
50
    @DELETE
51
    @Path("{id}")
52
    public void delete(@PathParam("id") String id) {
53
        repository.deleteById(id);
54
    }
55
}



The application is ready to run locally; we have either the docker image or install manually option to run a MongoDB instance and have fun.

In this tutorial, we'll move our application in the next step, moving it to the cloud, thanks to Platform.sh, where we need three files:

1) One Yaml files that have the application descriptions, such as the language, language version, who to build an application, and finally, how to execute it.

YAML
 




xxxxxxxxxx
1
10


 
1
name: app
2
type: "java:11"
3
disk: 1024
4
hooks:
5
    build:  mvn clean package payara-micro:bundle
6
relationships:
7
    mongodb: 'mongodb:mongodb'
8
web:
9
    commands:
10
        start: java -jar $JAVA_OPTS $CREDENTIAL target/microprofile-microbundle.jar --port $PORT



2) One to determine the services that your application need, yeap, don't worry about how to handle and maintain it, Platform.sh handles that to us.

YAML
 




xxxxxxxxxx
1


 
1
mongodb:
2
  type: mongodb:3.6
3
  disk: 1024



3) The last you explain the routes

YAML
 




xxxxxxxxxx
1


 
1
"https://{default}/":
2
  type: upstream
3
  upstream: "app:http"
4

          
5
"https://www.{default}/":
6
  type: redirect
7
  to: "https://{default}/"



It is easy, isn't it? MapStruct allows a unique interface to create an optimized mapper in the Java world. It does not use reflections, therefore, it won't have the same issues that brings with reflection use. Software Architecture is about to take and understand the trade-off in any kind of situation.

application Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus
  • Dust Actors and Large Language Models: An Application
  • Five Java Developer Must-Haves for Ultra-Fast Startup Solutions

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!