Your approach (directly modifying the entity within a transaction) is more efficient, simpler, and cleaner. On the other hand, your colleague’s approach is redundant in most cases, though useful when enforcing strict separation between data layers or when using immutable DTOs for business logic transformations. Why?
In Spring Boot with Hibernate, entities are managed within the persistence context when retrieved inside a transaction. Any changes made to an entity will be automatically persisted at the end of the transaction without needing an explicit save()
, thanks to dirty checking.
Your colleague's approach (entity → DTO → modify DTO → DTO → entity → save
) results in unnecessary object creation and extra processing, leading to increased CPU and memory usage.
Using EAGER fetching by default can lead to unnecessary data being loaded, especially for deeply nested objects, increasing query execution time.
Your approach with LAZY fetching ensures that only the necessary data is loaded, improving efficiency.
For API responses: DTOs help avoid exposing entity structures directly.
For projections or transformations: If the data needs to be reshaped, DTOs are a good choice.
For external system integrations: When working with external APIs, DTOs provide a stable contract.
However, for modifying and persisting entities, DTOs should not be mandatory unless:
The DTO encapsulates fields that shouldn’t be directly mapped to an entity (e.g., some computed fields).
The update process involves a separate layer of validation or business logic that should not interact directly with entities.
Your approach should be significantly faster because it avoids unnecessary object transformations and repo.save()
.
The only scenario where converting to a DTO and back might be useful is when performing complex updates involving multiple entities, ensuring that only modified fields are applied in a controlled manner.