Dto java spring boot

Knowledge Factory

Learn Java, Spring Boot, Quarkus, Kotlin, Go, Python, Angular, Vue.js, React.js, React Native, PHP, .Net and even more with CRUD example.

Java Record as DTO in Spring Boot Application

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Hello everyone, In this article, we will show how we used Java Record as DTO in the Spring Boot application. The GitHub repository link is provided at the end of this tutorial. You can download the source code.

From Java 14 onwards, the record is a special type of class declaration aimed at reducing the boilerplate code.

Technologies used :

Final Project Directory

Maven[pom.xml]

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details utilized by Maven to build the project.

version="1.0" encoding="UTF-8"?>
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot
spring-boot-starter-parent
2.6.3
/>
spring-boot-java-record
spring-boot-java-record
0.0.1-SNAPSHOT
spring-boot-java-record
Demo project for Spring Boot

17

org.springframework.boot
spring-boot-starter-data-jpa

org.springframework.boot
spring-boot-starter-web

com.h2database
h2
runtime
org.springframework.boot
spring-boot-starter-test
test


org.springframework.boot
spring-boot-maven-plugin

Creating the Entity User

Records cannot be used as entities with JPA/Hibernate. JPA entities must have a no-args constructor, and must not be final, two requirements that the record will not support. More Information

package com.knf.dev.demo.springbootjavarecord.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;

public User()
super();
>

public Long getId()
return id;
>

public void setId(Long id)
this.id = id;
>

public String getFirstName()
return firstName;
>

public void setFirstName(String firstName)
this.firstName = firstName;
>

public String getLastName()
return lastName;
>

public void setLastName(String lastName)
this.lastName = lastName;
>

public String getEmail()
return email;
>

public void setEmail(String email)
this.email = email;
>

public User(String firstName,
String lastName, String email)
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
>

>

Creating the User Repository

package com.knf.dev.demo.springbootjavarecord.repsitory;

import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.knf.dev.demo.springbootjavarecord.entity.User;

@Repository
public interface UserRepository
extends CrudRepositoryUser, Long>
ListUser> findAll();
>

Creating the User Service

package com.knf.dev.demo.springbootjavarecord.service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.knf.dev.demo.springbootjavarecord.dto.User;
import com.knf.dev.demo.springbootjavarecord.repsitory.UserRepository;

@Service
public class UserService
@Autowired
UserRepository repsoitory ;

//User mapper
public User mapUser(com.knf.dev.demo.
springbootjavarecord.
entity.User user)
User userDto = new User(user.getId(),
user.getFirstName(),
user.getLastName(),
user.getEmail());
return userDto;
>

public ListUser> getAllUsers()
//Fetch all users
List
springbootjavarecord.
entity.User> users = repsoitory.findAll();

//converting list of user entity to
// list of user record using java stream
return users.stream().
map(this::mapUser).
collect(Collectors.toList());
>

public User getUserById(Long id)
// Fetch user by id
Optional
springbootjavarecord.
entity.User> user
= repsoitory.findById(id);

// converting user entity to
// user record
return mapUser(user.get());
>
>

Java Record as DTO

package com.knf.dev.demo.springbootjavarecord.dto;

public record
User(Long id, String firstName,
String lastName, String email)
>

User Rest Controller

The @RestController annotation was introduced in Spring 4.0 to simplify the engendering of RESTful web services. It’s a convenience annotation that combines @Controller and @ResponseBody. @RequestMapping annotation maps HTTP requests to handler methods of MVC and REST controllers.

package com.knf.dev.demo.springbootjavarecord.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.knf.dev.demo.springbootjavarecord.dto.User;
import com.knf.dev.demo.springbootjavarecord.service.UserService;

@RestController
@RequestMapping("/api/v1/users")
public class UserController
@Autowired
UserService userService;

@GetMapping
public ListUser> getAllUsers()
return userService.getAllUsers();
>

@GetMapping("/")
public User getUSerById(@PathVariable Long id)
return userService.getUserById(id);
>
>

Spring Boot main driver

package com.knf.dev.demo.springbootjavarecord;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.knf.dev.demo.springbootjavarecord.entity.User;
import com.knf.dev.demo.springbootjavarecord.repsitory.UserRepository;

@SpringBootApplication
public class SpringBootJavaRecordApplication
implements CommandLineRunner
@Autowired
UserRepository repository;

public static void main(String[] args)
SpringApplication.
run(SpringBootJavaRecordApplication.class, args);
>

@Override
public void run(String. args) throws Exception //Inserting dummy data
User user1 =
new User("dummy user",
"dummy lastname", "dummy@gmail.com");
User user2 =
new User("dummy user 2",
"dummy lastname 2", "dummy@gmail2.com");
ListUser> users = new ArrayListUser>();
users.add(user2);
users.add(user1);
repository.saveAll(users);

>
>

Источник

Java Guides

In the previous tutorial, we created a Spring boot project and build CRUD RESTful Webservices using Spring Boot 3, Spring Data JPA (Hibernate), and MySQL database.

In this tutorial, we will see how to DTO (Data Transfer Object) pattern to transfer the data between the Client and Server in the Spring boot application.

DTO ( Data Transfer Object) Overview

Data Transfer Object Design Pattern is a frequently used design pattern. It is basically used to pass data with multiple attributes in one shot from client to server, to avoid multiple calls to a remote server.

Another advantage of using DTOs on RESTful APIs written in Java (and on Spring Boot), is that they can help to hide implementation details of domain objects (JPA entities). Exposing entities through endpoints can become a security issue if we do not carefully handle what properties can be changed through what operations.

Prerequisites

This tutorial is a continuation of Spring Boot 3 CRUD RESTful WebServices with MySQL Database tutorial so first, you need to create a Spring Boot project with CRUD REST API’s using this tutorial:

Development Steps

1. Create UserDto Class

package net.javaguides.springboot.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Setter @Getter @NoArgsConstructor @AllArgsConstructor public class UserDto

2. Change CRUD REST API’s to Return UserDTO to the Client

package net.javaguides.springboot.controller; import lombok.AllArgsConstructor; import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.User; import net.javaguides.springboot.exception.ErrorDetails; import net.javaguides.springboot.exception.ResourceNotFoundException; import net.javaguides.springboot.service.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.WebRequest; import java.time.LocalDateTime; import java.util.List; @RestController @AllArgsConstructor @RequestMapping("api/users") public class UserController < private UserService userService; // build create User REST API @PostMapping public ResponseEntitycreateUser(@RequestBody UserDto user)< UserDto savedUser = userService.createUser(user); return new ResponseEntity<>(savedUser, HttpStatus.CREATED); > // build get user by id REST API // http://localhost:8080/api/users/1 @GetMapping("") public ResponseEntity getUserById(@PathVariable("id") Long userId)< UserDto user = userService.getUserById(userId); return new ResponseEntity<>(user, HttpStatus.OK); > // Build Get All Users REST API // http://localhost:8080/api/users @GetMapping public ResponseEntity getAllUsers() < Listusers = userService.getAllUsers(); return new ResponseEntity<>(users, HttpStatus.OK); > // Build Update User REST API @PutMapping("") // http://localhost:8080/api/users/1 public ResponseEntity updateUser(@PathVariable("id") Long userId, @RequestBody UserDto user)< user.setId(userId); UserDto updatedUser = userService.updateUser(user); return new ResponseEntity<>(updatedUser, HttpStatus.OK); > // Build Delete User REST API @DeleteMapping("") public ResponseEntity deleteUser(@PathVariable("id") Long userId)< userService.deleteUser(userId); return new ResponseEntity<>("User successfully deleted!", HttpStatus.OK); > >

3. Create UserMapper Class

Let’s create a UserMapper class to convert the User entity to UserDto and UserDto to the User entity:

package net.javaguides.springboot.mapper; import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.User; public class UserMapper < // Convert User JPA Entity into UserDto public static UserDto mapToUserDto(User user)< UserDto userDto = new UserDto( user.getId(), user.getFirstName(), user.getLastName(), user.getEmail() ); return userDto; >// Convert UserDto into User JPA Entity public static User mapToUser(UserDto userDto) < User user = new User( userDto.getId(), userDto.getFirstName(), userDto.getLastName(), userDto.getEmail() ); return user; >>

4. Change Service Layer to use UserDto

Change UserService Interface

package net.javaguides.springboot.service; import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.User; import java.util.List; public interface UserService < UserDto createUser(UserDto user); UserDto getUserById(Long userId); ListgetAllUsers(); UserDto updateUser(UserDto user); void deleteUser(Long userId); >

Change UserServiceImpl 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.mapper.UserMapper; import net.javaguides.springboot.repository.UserRepository; import net.javaguides.springboot.service.UserService; import org.apache.logging.log4j.util.Strings; 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; @Override public UserDto createUser(UserDto userDto) < // Convert UserDto into User JPA Entity User user = UserMapper.mapToUser(userDto); User savedUser = userRepository.save(user); // Convert User JPA entity to UserDto UserDto savedUserDto = UserMapper.mapToUserDto(savedUser); return savedUserDto; >@Override public UserDto getUserById(Long userId) < OptionaloptionalUser = userRepository.findById(userId); User user = optionalUser.get(); return UserMapper.mapToUserDto(user); > @Override public List getAllUsers() < Listusers = userRepository.findAll(); return users.stream().map(UserMapper::mapToUserDto) .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); >@Override public void deleteUser(Long userId) < userRepository.deleteById(userId); >>

5. Test CRUD REST API’s using Postman Client

Источник

Читайте также:  Php header content type error
Оцените статью