Member-only story

Spring Boot Best Practices: Use DTOs Instead of Entities in API Responses

Learn why exposing JPA entities is bad and how to use DTOs in Spring Boot for secure, optimized APIs.

Ramesh Fadatare
3 min readJust now

When building REST APIs in Spring Boot, many developers directly return JPA entities in API responses.

This may seem easy, but it’s a bad practice because it can:
Expose sensitive fields (Security risk)
Cause lazy loading issues (Performance impact)
Tightly couple database structure with the API

💡 Solution? Use DTOs (Data Transfer Objects) instead of entities in responses.

In this guide, you’ll learn:
✅ Why exposing JPA entities is dangerous
✅ How DTOs improve API security and performance
✅ How to combine multiple entities into a single DTO
✅ A complete Spring Boot example with best practices

🚨 Problem: Exposing Entities Can Leak Sensitive Data

Let’s say we have a User entity representing database records:

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String username;
private String email;
private String password; // 🚨 Sensitive data…

--

--

No responses yet