Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 26

Manual JPA Entity to DTO Mapping

This lesson is built with resources from youtube.com, bell-sw.com and 1 more site.

Hello! Let's get started.

In our last lesson, we built powerful queries to fetch specific User and Post entities from the database. Our API can now find data, but we're sending back the raw JPA entity objects. This is a common practice in quick prototypes but introduces significant problems in production systems.

Today, we'll fix that. This lesson addresses the learning outcome: Implement a manual mapping strategy to convert between JPA entities and DTOs in the service layer. We will create a clean, secure, and stable API contract by separating our internal data model (entities) from the data structure we expose to the outside world (DTOs).

The Problem with Returning Entities

Returning JPA entities directly from your controllers creates several issues:

  1. Security Vulnerabilities: You risk exposing sensitive data. Our User entity contains a password field. Even though it's hashed, it should never leave the server.
  2. Unstable API Contract: Your API becomes tightly coupled to your database schema. If you add a new internal-only field to the User entity (e.g., lastLoginIp), it immediately leaks into your API response, potentially breaking clients who aren't expecting it.
  3. Inefficient Data Transfer: You might send more data than the client needs (over-fetching) or structure the data in a way that forces the client to make multiple requests to get what it wants.

This diagram illustrates the separation we want to achieve. The client and controller should speak in the language of DTOs, while the service and repository layers work with entities.

Data Flow in Layered Application Architecture with DTOs and Entities
This diagram shows the flow of data in a layered application. The client interacts with the Controller using DTOs. The Controller passes these to the Service. The Service uses a Mapper to convert DTOs to Entities to work with the Repository and Database, and converts Entities back to DTOs before returning data to the Controller.

MERN vs. Spring Boot: API Data Shaping

In your MERN stack experience, you've likely handled this implicitly. In an Express.js route handler, you might manually construct an object to send back, carefully picking which properties from your Mongoose model to include. For example:

// You might do this in Express to avoid sending the password
const user = await User.findById(req.params.id);
res.json({ 
  id: user._id, 
  name: user.name, 
  email: user.email 
});

This is the DTO pattern in action. Because Java is strongly typed, we formalize this by creating dedicated classes for these data transfer structures. These are our Data Transfer Objects (DTOs).


Why DTOs are Essential

To see a practical demonstration of the problem and the DTO solution, let's watch a short video.

JAVA DTO Pattern Tutorial | Simplify Your Code

The video 'JAVA DTO Pattern Tutorial' from Amigoscode clearly demonstrates why exposing entities is a bad idea and walks through the process of creating and using DTOs.

Please watch from 02:01 to 11:07. Focus on: The conceptual explanation of why DTOs are needed (02:01 - 04:30). The concrete example of a password hash being exposed in an API response (04:30 - 05:26). How a CustomerDTO is created using a Java record to select specific fields (07:23 - 08:48). The process of modifying the service layer to map the entity to the DTO using a Java Stream (08:48 - 11:07).

As the video shows, DTOs give us full control over our API's "shape," ensuring we only expose what's necessary.


Manual Mapping: The Foundation

While there are libraries that can automate this mapping, understanding how to do it manually is a fundamental skill. It gives you full control and makes debugging much easier. Let's get our hands dirty.

For a detailed textual guide on the manual mapping strategy we're about to implement, the following article is an excellent resource.

Ultimate Guide to Using DTOs with Spring Boot - BellSoft

The 'Ultimate Guide to Using DTOs with Spring Boot' from BellSoft provides a comprehensive overview. We'll focus on the sections that define DTOs with modern Java records and show the manual mapping implementation.

Please read the sections "What Are DTOs (Data Transfer Objects)?", "DTOs with Modern Java: Using Records", and "Mapping Entities to DTOs: Manual Mapping". These sections will provide the theoretical and practical foundation for the code we are about to write.


Hands-On: Implementing Manual Mappers

Let's apply these concepts to our blog platform.

Step 1: Create the DTOs

First, create a new package com.example.blogplatform.dto. Inside this package, we'll define our DTOs using Java records. Records are perfect for this as they are simple, immutable data carriers.

  1. UserResponseDTO.java: This will represent a user in API responses.

    package com.example.blogplatform.dto;
    
    public record UserResponseDTO(
            Long id,
            String firstName,
            String lastName,
            String email
    ) {
    }
    

    Notice: No password field!

  2. PostResponseDTO.java: This will represent a blog post and will include information about the author, demonstrating a nested DTO.

    package com.example.blogplatform.dto;
    
    import java.time.LocalDateTime;
    
    public record PostResponseDTO(
            Long id,
            String title,
            String content,
            LocalDateTime createdAt,
            UserResponseDTO author
    ) {
    }
    

Step 2: Create the Mapper Components

Next, create a new package com.example.blogplatform.mapper. Mappers will be Spring components responsible for the conversion logic.

  1. UserMapper.java: This component will handle User entity conversions.

    package com.example.blogplatform.mapper;
    
    import com.example.blogplatform.domain.User;
    import com.example.blogplatform.dto.UserResponseDTO;
    import org.springframework.stereotype.Component;
    
    @Component
    public class UserMapper {
    
        public UserResponseDTO toDto(User user) {
            if (user == null) {
                return null;
            }
            return new UserResponseDTO(
                    user.getId(),
                    user.getFirstName(),
                    user.getLastName(),
                    user.getEmail()
            );
        }
    }
    
  2. PostMapper.java: This mapper will convert a Post entity. It needs to convert the associated User as well, so we'll inject the UserMapper.

    package com.example.blogplatform.mapper;
    
    import com.example.blogplatform.domain.Post;
    import com.example.blogplatform.dto.PostResponseDTO;
    import org.springframework.stereotype.Component;
    
    @Component
    public class PostMapper {
    
        private final UserMapper userMapper;
    
        public PostMapper(UserMapper userMapper) {
            this.userMapper = userMapper;
        }
    
        public PostResponseDTO toDto(Post post) {
            if (post == null) {
                return null;
            }
            return new PostResponseDTO(
                    post.getId(),
                    post.getTitle(),
                    post.getContent(),
                    post.getCreatedAt(),
                    userMapper.toDto(post.getUser()) // Here we reuse the UserMapper
            );
        }
    }
    

    This demonstrates a key principle: composition. Mappers for complex objects can be built by composing simpler mappers.

Step 3: Update the Service and Controller

Now, let's use our mappers. We'll refactor the endpoint that fetches a single post.

  1. Update PostService.java
    Inject PostMapper and change findPostById to return a PostResponseDTO.

    // In PostService.java
    
    private final PostRepository postRepository;
    private final PostMapper postMapper; // Add this
    
    // Update constructor
    public PostService(PostRepository postRepository, PostMapper postMapper) {
        this.postRepository = postRepository;
        this.postMapper = postMapper; // Add this
    }
    
    // Update the method signature and implementation
    public PostResponseDTO findPostById(Long id) {
        Post post = postRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Post not found with id: " + id));
        return postMapper.toDto(post);
    }
    
  2. Update PostController.java (Assuming you have one)
    The controller now receives the DTO from the service, so we just need to update the method's return type.

    // In a PostController.java
    
    @GetMapping("/{id}")
    public ResponseEntity<PostResponseDTO> getPostById(@PathVariable Long id) {
        PostResponseDTO postDto = postService.findPostById(id);
        return ResponseEntity.ok(postDto);
    }
    

Debugging-First: See the Transformation Live

Let's verify our work by observing the application at runtime.

  1. Set Breakpoints:
    • In your PostController, place a breakpoint on the line return ResponseEntity.ok(postDto);.
    • In your PostMapper, place a breakpoint inside the toDto method, on the line return new PostResponseDTO(...).
  2. Run in Debug Mode: Start your Spring Boot application in debug mode from your IDE.
  3. Make a Request: Use Postman or your browser to make a GET request to an existing post's endpoint (e.g., http://localhost:8080/api/posts/1).
  4. Observe:
    • The execution will first pause in PostMapper. Inspect the post variable. You will see the full Post entity, which contains the User entity, which in turn contains the password field.
    • Resume execution (F9 or F8 to step over).
    • The execution will now pause in PostController. Inspect the postDto variable. You will see our clean PostResponseDTO. Expand it to see the author field, which is a UserResponseDTO—no password in sight!

This exercise confirms that our mapping logic is working correctly, intercepting the entity and transforming it into a safe, contract-defined DTO before it's sent to the client.


Conclusion

Excellent work! You've implemented one of the most critical patterns in backend development. By separating your internal domain models from your public API contracts, you've made your application more secure, robust, and maintainable.

Key Takeaways:

  • DTOs define your API contract. They decouple the client from your internal database structure.
  • Use DTOs to prevent leaking sensitive data like passwords and to create stable, versionable APIs.
  • Java records are a modern and effective way to define immutable DTOs.
  • Manual mappers are simple classes (ideally Spring @Components) that contain the logic to transform entities to DTOs.
  • Mapper composition (a mapper using another mapper) is a powerful pattern for handling nested objects and keeping your code DRY (Don't Repeat Yourself).

Preview of the Next Lesson:

Our PostMapper currently accesses post.getUser() to get the author's information. This seems harmless, but what happens when we fetch a list of 50 posts? Does Spring Data JPA fetch the 50 posts and then make 50 additional queries to get each post's author? This is the infamous N+1 query problem, a performance killer. In our next lesson, we will learn how to detect this problem by analyzing our SQL logs and how to solve it efficiently using a JOIN FETCH strategy.