Last updated on March 4th, 2025
In Spring Boot, DTO and Entity are commonly used key concepts. While using these commonly there is some difference between DTO and Entity. Entity is a Java class that creates a table in the database by using JPA annotations and DTO is also a class used to transfer data between layers. This topic will explain the difference between DTO and Entity, their use cases and best practices to understand for using them effectively in our Spring Boot application.
What is an Entity in Spring Boot?
A Java Bean class annotated with JPA annotations(@Entity, @Id, etc.) makes the table in the database that is called Entity in Spring Boot. It is also used in JPA (Java Persistence API) for object-relational mapping (ORM), operations and defining queries. It’s each instance corresponds to a row in the database table.
Key Features of an Entity
- It maps Java classes to database tables.
- It enables persistence, retrieval, and manipulation of data through JPA repositories.
- It uses these annotations(@OneToMany, @ManyToOne, etc.) for making relationships between database tables.
- It uses these JPA annotations (@Entity, @Id, etc.) for database mapping and @NamedQuery and @NamedNativeQuery for adding queries.
Example: Entity in Spring Boot
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and Setters
}
What is a DTO in Spring Boot?
A POJO class in the Spring Boot application used to transfer data from one layer to different layers is called DTO(Data Transfer Object).
Key Features of a DTO
- It is used to carry data between layers, especially in API responses and requests.
- It decouples the internal database structure (entities) from external clients.
- It often contains only the necessary fields for specific use cases.
Example: DTO in Spring Boot
public class ProductDTO {
private Long id;
private String name;
// Setter and Getter
}
- We can use Lombok annotation to automatically generate setter and getter methods and etc.
Key Difference Between DTO and Entity
Feature | Entity | DTO |
Purpose | It represents a table in the database. | It represents data for transfer between application layers. |
Database Mapping | It mapped to a database table using JPA annotations. | It is not mapped to the database. |
Relationship Handling | It supports relationships between entities (e.g., @OneToMany). | It does not handle relationships directly. |
Dependency | It is part of the persistence layer and tightly coupled with the database. | It is the part of the presentation or service layer, that is decoupled from the database. |
Fields | It contains all fields required for database representation. | It contains only fields required for specific use cases. |
Annotations | It uses JPA annotations like @Entity, @Id, and @Table and may use Lombok annotations. | It may use Lombok annotations like @Data or @Getter. |
Use Case | It is used for database persistence and retrieval. | It is used for transferring data, especially in APIs. |
When to Use DTO
- API Responses and Requests: Use DTOs to send and receive data in REST APIs, isolating internal entity structure from clients.
- Decoupling: Prevent exposing your entity’s database structure to external systems.
- Custom Representations: Create different DTOs for different use cases (e.g., a subset of fields).
Example: Using DTO in a Controller
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/{id}")
public ProductDTO getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
}
When to Use Entity
- Database Persistence: Use entities for all database interactions.
- Relational Mapping: Define relationships between tables, such as @OneToMany or @ManyToOne.
- CRUD Operations: Use entities with JPA repositories to handle database operations.
Example: Using Entity in a Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// JPA methods for CRUD operations
}
How to Convert Between DTO and Entity
To convert between entities and DTOs in the Spring Boot application, we can use tools like ModelMapper, MapStruct, or manual mapping methods.
Example: Manual Mapping
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public ProductDTO getProductById(Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Product not found"));
// Manual mapping
ProductDTO productDTO = new ProductDTO();
productDTO.setId(product.getId());
productDTO.setName(product.getName());
return productDTO;
}
}
Example: Using ModelMapper
import org.modelmapper.ModelMapper;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Autowired
private ModelMapper modelMapper;
public ProductDTO getProductById(Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Product not found"));
return modelMapper.map(product, ProductDTO.class);
}
}
Best Practices
- Keep DTOs and Entities Separate: Avoid using entities directly in the controller or exposing them in API responses.
- Custom DTOs for Specific Use Cases: Create different DTOs for different API endpoints as needed.
- Use Mapping Tools: Use libraries like ModelMapper or MapStruct for efficient and error-free mapping between DTOs and entities.
- Avoid Business Logic in DTOs: Keep DTOs lightweight and only include fields required for the specific use case.
Practical Comparison
Scenario | Entity | DTO |
Database interactions | Use entities for database operations. | Not applicable. |
API responses | Avoid exposing entities in APIs. | Use DTOs to send data to external clients. |
Custom representations | Not suitable for custom fields. | Suitable for custom data representations. |
Relational mapping | Supports table relationships. | Does not handle relationships directly. |
Conclusion
In Spring Boot, DTOs and Entities play complementary roles in creating clean, maintainable, and efficient applications:
- Entities handle database interactions and represent the data at the persistence layer.
- DTOs are focused on transferring data between application layers, especially in APIs.