🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In a previous couple of tutorials, we created a Spring boot project and Built CRUD Restful web services with DTO.
Refer to previous tutorials:
Spring Boot 3 CRUD RESTful WebServices with MySQL Database
Spring Boot DTO Example Tutorial
In this tutorial, we will learn how to use the ModelMapper library to map the JPA entity into DTO and vice versa.
ModelMapper Library Overview
ModelMapper is a lightweight Java library used for object mappings.
The goal of ModelMapper is to make object mapping easy, by automatically determining how one object model maps to another, based on conventions, in the same way, that a human would - while providing a simple, refactoring-safe API for handling specific use cases.
Read more about ModelMapper at the official website: http://modelmapper.org/getting-started/
Prerequisites
This tutorial is a continuation of below two tutorials so first, create CRUD REST APIs using below tutorials:
Spring Boot 3 CRUD RESTful WebServices with MySQL Database
Spring Boot DTO Example Tutorial
Check out the complete source code of this tutorial is available on my GitHub repository at Spring Boot CRUD RESTful WebServices
Development Steps
1. Add Maven Dependency
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.0</version>
</dependency>2. Configure ModelMapper class a Spring Bean
package net.javaguides.springboot;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringbootRestfulWebservicesApplication {
@Bean
public ModelMapper modelMapper(){
return new ModelMapper();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootRestfulWebservicesApplication.class, args);
}
} @Bean
public ModelMapper modelMapper(){
return new ModelMapper();
}3. Inject and Use ModelMapper Spring Bean in Service Class
package net.javaguides.springboot.service.impl;
import lombok.AllArgsConstructor;
import net.javaguides.springboot.dto.UserDto;
import net.javaguides.springboot.entity.User;
import net.javaguides.springboot.exception.EmailAlreadyExistsException;
import net.javaguides.springboot.exception.ResourceNotFoundException;
import net.javaguides.springboot.mapper.UserMapper;
import net.javaguides.springboot.repository.UserRepository;
import net.javaguides.springboot.service.UserService;
import org.apache.logging.log4j.util.Strings;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
private ModelMapper modelMapper;
@Override
public UserDto createUser(UserDto userDto) {
// Convert UserDto into User JPA Entity
// User user = UserMapper.mapToUser(userDto);
User user = modelMapper.map(userDto, User.class);
User savedUser = userRepository.save(user);
// Convert User JPA entity to UserDto
//UserDto savedUserDto = UserMapper.mapToUserDto(savedUser);
UserDto savedUserDto = modelMapper.map(savedUser, UserDto.class);
return savedUserDto;
}
@Override
public UserDto getUserById(Long userId) {
User user = userRepository.findById(userId).get();
//return UserMapper.mapToUserDto(user);
return modelMapper.map(user, UserDto.class);
}
@Override
public List<UserDto> getAllUsers() {
List<User> users = userRepository.findAll();
// return users.stream().map(UserMapper::mapToUserDto)
// .collect(Collectors.toList());
return users.stream().map((user) -> modelMapper.map(user, UserDto.class))
.collect(Collectors.toList());
}
@Override
public UserDto updateUser(UserDto user) {
User existingUser = userRepository.findById(user.getId()).get();
existingUser.setFirstName(user.getFirstName());
existingUser.setLastName(user.getLastName());
existingUser.setEmail(user.getEmail());
User updatedUser = userRepository.save(existingUser);
//return UserMapper.mapToUserDto(updatedUser);
//return modelMapper.map(updatedUser, UserDto.class);
}
@Override
public void deleteUser(Long userId) {
userRepository.deleteById(userId);
}
}4. Test CRUD REST APIs using Postman Client
Create User REST API:
Request Body:
{
"firstName": "ramesh",
"lastName":"fadatare",
"email": "ramesh@gmail.com"
}Refer to this screenshot to test Create User REST API:Get User REST API:
Update User REST API:
Request Body:
{
"firstName": "ram",
"lastName":"fadatare",
"email": "ram@gmail.com"
}Refer to this screenshot to test the Update User REST API:Get All Users REST API:
DELETE User REST API:
Source Code on GitHub
The source code of this tutorial is available on my GitHub repository at Spring Boot CRUD RESTful WebServices
Conclusion
Further Reading
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business





Comments
Post a Comment
Leave Comment