0% found this document useful (0 votes)
5 views

Data Transfer Objects

Data Transfer Objects (DTOs) in Java are plain classes used to transfer data between application layers while keeping internal business logic hidden. They enhance security by preventing exposure of sensitive fields, improve performance by reducing unnecessary data in API responses, and are commonly utilized in REST APIs. DTOs can be used for both input and output data, allowing for a clear separation between API models and database entities.

Uploaded by

saihari292
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Data Transfer Objects

Data Transfer Objects (DTOs) in Java are plain classes used to transfer data between application layers while keeping internal business logic hidden. They enhance security by preventing exposure of sensitive fields, improve performance by reducing unnecessary data in API responses, and are commonly utilized in REST APIs. DTOs can be used for both input and output data, allowing for a clear separation between API models and database entities.

Uploaded by

saihari292
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Data Transfer Objects (DTOs) in Java

What is a DTO?

A Data Transfer Object (DTO) is a plain Java class used to transfer data between different
layers of an application without exposing internal business logic. DTOs do not contain
business logic—they only hold data.

1. Why Use DTOs?

✅ Decoupling: Separates data representation from business logic.


✅ Security: Prevents exposing sensitive fields of entity classes.
✅ Performance: Reduces unnecessary data exposure in API responses.
✅ Serialization: DTOs are used in REST APIs for JSON/XML data exchange.

2. Basic DTO Example

Let’s consider a User Management System where we fetch user data but don’t expose
internal system fields.

Entity Class (Represents Database Table)

class UserEntity {

private Long id;

private String username;

private String password; // Sensitive, should not be exposed

private String email;

public UserEntity(Long id, String username, String password, String email) {

this.id = id;

this.username = username;

this.password = password;

this.email = email;

// Getters
public Long getId() { return id; }

public String getUsername() { return username; }

public String getPassword() { return password; }

public String getEmail() { return email; }

DTO Class (Only Exposes Required Data)

class UserDTO {

private String username;

private String email;

public UserDTO(String username, String email) {

this.username = username;

this.email = email;

// Getters

public String getUsername() { return username; }

public String getEmail() { return email; }

🔹 Why?

 UserDTO does NOT contain password, keeping it secure.

 Only required data (username, email) is transferred.

3. Converting Entity to DTO

Use a converter method to map an Entity to a DTO.

class UserMapper {

public static UserDTO toDTO(UserEntity user) {

return new UserDTO(user.getUsername(), user.getEmail());


}

4. Using DTOs in a REST API (Spring Boot Example)

DTOs are commonly used in Spring Boot REST APIs to send responses.

Controller Example

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping("/users")

public class UserController {

@GetMapping("/{id}")

public UserDTO getUser(@PathVariable Long id) {

// Simulating fetching data from a database

UserEntity user = new UserEntity(id, "JohnDoe", "secure123", "[email protected]");

// Convert Entity to DTO

return UserMapper.toDTO(user);

Example API Response (JSON Output)

When calling GET /users/1, we get:

"username": "JohnDoe",

"email": "[email protected]"

🔹 Why?
 Password is hidden—it is NOT included in the response.

5. Using DTOs with Collections

If we need to send multiple users:

import java.util.List;

import java.util.stream.Collectors;

class UserService {

public List<UserDTO> getAllUsers() {

List<UserEntity> users = List.of(

new UserEntity(1L, "Alice", "pass123", "[email protected]"),

new UserEntity(2L, "Bob", "pass456", "[email protected]")

);

return users.stream().map(UserMapper::toDTO).collect(Collectors.toList());

6. DTOs in Database Operations (JPA & Spring Boot)

In Spring Boot + JPA, we can use DTOs for optimized database queries.

DTO Projection with JPA

public interface UserRepository extends JpaRepository<UserEntity, Long> {

// Select only required fields instead of fetching full entity

@Query("SELECT new UserDTO(u.username, u.email) FROM UserEntity u WHERE u.id


= :id")

UserDTO findUserDTOById(@Param("id") Long id);

}
🔹 Why?

 Prevents fetching unnecessary data from the database.

 Improves performance.

7. DTOs for Request and Response

Separate DTOs for Input & Output

In APIs, we use:

 UserRequestDTO for receiving data (POST /users)

 UserResponseDTO for sending data (GET /users/{id})

Example

class UserRequestDTO {

private String username;

private String email;

private String password; // Needed for registration

class UserResponseDTO {

private String username;

private String email;

8. DTOs vs. Entity – When to Use?

Aspect DTO Entity (JPA Model)

Purpose Transfers data Represents database table

Contains Logic? No (only data) Yes (business logic, relationships)

Security Can hide sensitive fields Exposes all fields

Performance Reduces data size Loads full object from DB

9. Summary
✔ Use DTOs to:

 Hide sensitive fields (password, credit card).

 Improve performance by fetching only required fields.

 Separate API models from database models.

🚀 Want me to generate a full Spring Boot project with DTOs? Let me know! 😊

You might also like