Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>>EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with SpringCloud:

>> Join Pro and download theeBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockitolibrary makes it easy to writeclean and intuitive unittests for your Java code.

Get started with mocking and improve your application testsusing ourMockito guide:

Download theeBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the SpringWebFlux module, which has been improved upon ever since. Getstarted with the Reactor project basics andreactive programmingin Spring Boot:

>> Join Pro anddownload the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download theE-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download theE-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download theE-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore theeBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through theLearnSpring course:

>> LEARNSPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building afullREST API with the framework:

>>The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advancedfunctionality within the Core to the deep OAuth support in theframework.

I built the security material astwo full courses - Core andOAuth, to get practical with these more complex scenarios. Weexplore when and how to use each feature andcode through it onthe backing project.

You can explore the course here:

>> Learn SpringSecurity

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle thecomplexity ofJPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided referencecourse:

>> CHECK OUT THECOURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — withOpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy toput off. That’s where OpenRewrite comes in. The open-sourceframework for large-scale, automated code transformations helpsteams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite atModerne run live, hands-on training sessions — one for newcomersand one for experienced users. You’ll see how recipes work, how toapply them across projects, and how to modernize code withconfidence.

Join the next session,bring your questions, and learn how to automate the kind of workthat usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the releaseprocess, to ensure that new code doesn't break the existingfunctionality. As the codebase evolves, we want to run these testsfrequently to help catch any issues early on.

The best way to ensure these tests run frequently on anautomated basis is, of course,to include them in the CI/CDpipeline. This way, the regression tests will executeautomatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests usingSelenium, and then include them in our pipelineusing GitHubActions:, to berun on the LambdaTest cloud grid:

>> How to Run SeleniumRegression Tests With GitHub Actions

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>> EXPLOREACCESS NOW

1. Overview

In this tutorial, we’ll handle the conversions that need to happenbetween the internal entities of a Spring application and the externalDTOs (Data Transfer Objects) that are published back to the client.

Further reading:

Spring's RequestBody and ResponseBody Annotations

Learn about the Spring @RequestBody and @ResponseBody annotations.

Quick Guide to MapStruct

A quick and practical guide to using MapStruct

2. Model Mapper

Let’s start by introducing the main library that we’re going to use to perform this entity-DTO conversion,ModelMapper.

We will need this dependency in thepom.xml:

<dependency>    <groupId>org.modelmapper</groupId>    <artifactId>modelmapper</artifactId>    <version>3.2.0</version></dependency>

To check if there’s any newer version of this library,go here.

Then we’ll define theModelMapper bean in our Spring configuration:

@Beanpublic ModelMapper modelMapper() {    return new ModelMapper();}

3. The DTO

Next let’s introduce the DTO side of this two-sided problem,Post DTO:

public class PostDto {    private static final SimpleDateFormat dateFormat      = new SimpleDateFormat("yyyy-MM-dd HH:mm");    private Long id;    private String title;    private String url;    private String date;    private UserDto user;    public Date getSubmissionDateConverted(String timezone) throws ParseException {        dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));        return dateFormat.parse(this.date);    }    public void setSubmissionDate(Date date, String timezone) {        dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));        this.date = dateFormat.format(date);    }    // standard getters and setters}

Note that the two custom date related methods handle the date conversion back and forth between the client and the server:

  • getSubmissionDateConverted() method converts dateString into aDate in the server’s timezone to use it in the persistingPost entity
  • setSubmissionDate() method is to set DTO’s date toPost‘sDate in current user timezone

4. The Service Layer

Now let’s look at a service level operation, which will obviously work with the Entity (not the DTO):

public List<Post> getPostsList(  int page, int size, String sortDir, String sort) {     PageRequest pageReq     = PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort);     Page<Post> posts = postRepository      .findByUser(userService.getCurrentUser(), pageReq);    return posts.getContent();}

We’re going to have a look at the layer above service next, the controller layer. This is where the conversion will actually happen.

5. The Controller Layer

Next let’s examine a standard controller implementation, exposing the simple REST API for thePost resource.

We’re going to show here a few simple CRUD operations: create, update, get one, and get all. Given that the operations are pretty straightforward,we are especially interested in the Entity-DTO conversion aspects:

@Controllerclass PostRestController {    @Autowired    private IPostService postService;    @Autowired    private IUserService userService;    @Autowired    private ModelMapper modelMapper;    @GetMapping    @ResponseBody    public List<PostDto> getPosts(...) {        //...        List<Post> posts = postService.getPostsList(page, size, sortDir, sort);        return posts.stream()          .map(this::convertToDto)          .collect(Collectors.toList());    }    @PostMapping    @ResponseStatus(HttpStatus.CREATED)    @ResponseBody    public PostDto createPost(@RequestBody PostDto postDto) {        Post post = convertToEntity(postDto);        Post postCreated = postService.createPost(post));        return convertToDto(postCreated);    }    @GetMapping(value = "/{id}")    @ResponseBody    public PostDto getPost(@PathVariable("id") Long id) {        return convertToDto(postService.getPostById(id));    }    @PutMapping(value = "/{id}")    @ResponseStatus(HttpStatus.OK)    public void updatePost(@PathVariable("id") Long id, @RequestBody PostDto postDto) {        if(!Objects.equals(id, postDto.getId())){            throw new IllegalArgumentException("IDs don't match");        }        Post post = convertToEntity(postDto);        postService.updatePost(post);    }}

Here isour conversion fromPost entity toPostDto:

private PostDto convertToDto(Post post) {    PostDto postDto = modelMapper.map(post, PostDto.class);    postDto.setSubmissionDate(post.getSubmissionDate(),         userService.getCurrentUser().getPreference().getTimezone());    return postDto;}

Here is the conversionfrom DTO to an entity:

private Post convertToEntity(PostDto postDto) throws ParseException {    Post post = modelMapper.map(postDto, Post.class);    post.setSubmissionDate(postDto.getSubmissionDateConverted(      userService.getCurrentUser().getPreference().getTimezone()));     if (postDto.getId() != null) {        Post oldPost = postService.getPostById(postDto.getId());        post.setRedditID(oldPost.getRedditID());        post.setSent(oldPost.isSent());    }    return post;}

So as we can see, with the help of the model mapper,the conversion logic is quick and simple. We’re using themap API of the mapper, and getting the data converted without writing a single line of conversion logic.

6. Unit Testing

Finally, let’s do a very simple test to make sure the conversions between the entity and the DTO work well:

public class PostDtoUnitTest {    private ModelMapper modelMapper = new ModelMapper();    @Test    public void whenConvertPostEntityToPostDto_thenCorrect() {        Post post = new Post();        post.setId(1L);        post.setTitle(randomAlphabetic(6));        post.setUrl("www.test.com");        PostDto postDto = modelMapper.map(post, PostDto.class);        assertEquals(post.getId(), postDto.getId());        assertEquals(post.getTitle(), postDto.getTitle());        assertEquals(post.getUrl(), postDto.getUrl());    }    @Test    public void whenConvertPostDtoToPostEntity_thenCorrect() {        PostDto postDto = new PostDto();        postDto.setId(1L);        postDto.setTitle(randomAlphabetic(6));        postDto.setUrl("www.test.com");        Post post = modelMapper.map(postDto, Post.class);        assertEquals(postDto.getId(), post.getId());        assertEquals(postDto.getTitle(), post.getTitle());        assertEquals(postDto.getUrl(), post.getUrl());    }}

7. Conclusion

In this article, we detailedsimplifying the conversion from Entity to DTO, and from DTO to Entity in a Spring REST API, by using the model mapper library instead of writing these conversions by hand.

The code backing this article is available on GitHub. Once you'relogged in as aBaeldung Pro Member, start learning and coding on the project.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>>EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

TheApache HTTP Client is a very robust library, suitablefor both simple and advanced use cases whentesting HTTPendpoints. Check out our guide covering basic request andresponse handling, as well as security, cookies, timeouts, andmore:

>> Downloadthe eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky processwith manypotential pitfalls. A solid grasp of thefundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications withourJava Concurrency guide:

>>Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring,through theLearn Spring course:

>> CHECK OUTTHE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebasesdon’t always keep up. Frameworks change, dependencies drift, andtech debt builds until it starts to drag on delivery. OpenRewritewas built to fix that: an open-source refactoring engine thatautomates repetitive code changes while keeping developer intentintact.

The monthly training series, led by the creators and maintainersof OpenRewrite at Moderne, walks through real-world migrations andmodernization patterns. Whether you’re new to recipes or ready towrite your own, you’ll learn practical ways to refactor safely andat scale.

If you’ve ever wished refactoring felt as natural — and as fast— as writing code,this is a goodplace to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>> EXPLOREACCESS NOW

Course – LS – NPI (cat=REST)
announcement - icon

Get started with Spring Boot and with core Spring,through theLearn Spring course:

>> CHECK OUT THECOURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
Do JSON right with Jackson - book cover
Do JSON right with Jackson - icon
Do JSON right with Jackson
Download the E-book