Javarevisited

A humble place to learn Java and Programming better.

Follow publication

Member-only story

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

Ramesh Fadatare
Javarevisited
Published in
3 min readFeb 25, 2025

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response