blog.stackademic.com-Builder Pattern in Spring Boot
blog.stackademic.com-Builder Pattern in Spring Boot
blog.stackademic.com/builder-pattern-in-spring-boot-6ed7b0e57e1f
Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to
democratize free coding education for the world.
Design Patterns offer established development paradigms, allowing developers to save time
by leveraging proven solutions instead of creating new patterns for each recurring problem,
one of Design Patterns is Builder Pattern.
The Builder Pattern is a creational design pattern that separates the construction of a
complex object from its representation. It provides a way to construct an object step by step,
allowing you to set its properties individually and ultimately obtain the fully-constructed
object.
1/6
Meet Differ: The Free AI-Powered Blogging Platform
String { name; }
String { surname; }
User {(); } }}
2/6
{
System.out.println(user.toString()); }}
This code demonstrates how to create User objects with optional parameters using the
builder pattern, making the construction process more readable and maintainable. It allows
you to set attributes step by step and create a User object with the desired properties.
Use the builder pattern to avoid creating a large number of subclasses, to avoid having a
constructor with a large number of attributes, to avoid the telescopic constructor anti-pattern,
and to avoid creating too many constructors.
Integer id;
String username;
String email;
String password;
3/6
And we want to map User entity class attributes with UserDto class attributes so that we can
send only required attributes in our RESTful API request.
As one solution you can use MapStruct to automatically map attributes of User entity class
with UserDto class, but as it is a third party library it may cause problems in using of other
built-in libraries or third party libraries of Java.
Builder Pattern can help us in mapping these attributes by building a UserDto with
parameters set from User entity class.
If you are using Lombok in your Spring Boot application, you can use annotation to initialize
Concrete Builder to your Java classes or you can create your Concrete Builder as in
example above.
Firstly, we create a UserMapper class that will serve as a mapper to map attributes of
objects. As we will map attributes of User entity class with UserDto class, we create a
function with UserDto class type and a parameter with User entity class.
This function will create a UserDto object with builder pattern by setting it’s attributes from
User entity class attributes that will be passed as parameter.
We need to create a UserService class that will handle our business logic for User entity. We
want to find a User entity by it’s ID and return to client as a UserDto.
We will create a functionthat returns a UserDto and has an integer paremeter named id.
UserDto { userRepository.findById(id)
.orElseThrow(() -> (ErrorEnum.USER_NOT_FOUND));
userMapper.convertToDto(user); }
4/6
This function will use UserRepository that uses JPA Repository’s built-in function findById to
find a user by it’s id from database. This function will return a User entity if it exists in
database otherwise it will throw a custom exception created in application that will throw an
error that USER_NOT_FOUND with status code 404.
I will write an article about Exception Handling in Java Spring Boot and will explain about
creating custom exception handlers in later times and pass the link here if you want to read
about it.
Let’s say we found a User, as we will return as UserDto we should map User entity with
UserDto with our function created in UserMapper class.
As we created our service that will find a user by id and return it as UserDto, let’s create a
controller that will use this service.
UserService userService;
ResponseEntity<UserDto> {
ResponseEntity.ok(userService.getUserById(id)); }
UserController class will serve as a controller to handle requests and endpoints that will
come to our RESTful API.
We create a function that will be a GET request with endpoint , our id will be a path variable
that will be given by client when sending a request and it will be passed to our function
created in UserService class.
5/6
As seen in picture, we sent a request to our endpoint and returned a User with UserDto type
as a response.
You can use Builder Pattern to map attributes between two objects in your RESTful API
application and return them without of need to install any third-party libraries to your
application.
Stackademic 🎓
Thank you for reading until the end. Before you go:
6/6