Mapping between entities and DTOs
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite stores a cost price and timestamps that buyers must never see and clients must not set. If the controller returns or accepts the stored object directly, those fields leak in both directions.
Entity and DTO: different jobs, different fields
An entity is the object for one stored row, with every column, including internal ones. A DTO (data transfer object) is the object for one API message, with only the fields that message needs.
Here is one product as a request, an entity and a response. Compare which fields each one has.
Example 1 · One product as request, entity and response
import java.math.BigDecimal;import java.time.LocalDateTime;
// Entity: one stored row, every column, including internal onesclass Product { Long id; String sku; String name; BigDecimal price; BigDecimal costPrice; int stock; boolean active; LocalDateTime createdAt; LocalDateTime updatedAt;
@Override public String toString() { return "Product{id=" + id + ", sku=" + sku + ", name=" + name + ", price=" + price + ", costPrice=" + costPrice + ", stock=" + stock + ", active=" + active + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + "}"; }}
// Request DTO: what an admin sends to create a product (no id, no timestamps)record CreateProductRequest(String sku, String name, BigDecimal price, BigDecimal costPrice, int stock) {}
// Response DTO: what a buyer's app receives (no cost price, no timestamps)record ProductResponse(Long id, String sku, String name, BigDecimal price, int stock, boolean isActive) {}
public class EntityVsDtoDemo { public static void main(String[] args) { CreateProductRequest request = new CreateProductRequest("BK-CLEAN", "Clean Code", new BigDecimal("499.00"), new BigDecimal("310.00"), 30);
Product entity = new Product(); entity.id = 9L; entity.sku = request.sku(); entity.name = request.name(); entity.price = request.price(); entity.costPrice = request.costPrice(); entity.stock = request.stock(); entity.active = true; entity.createdAt = LocalDateTime.of(2026, 10, 16, 11, 30); entity.updatedAt = entity.createdAt;
ProductResponse response = new ProductResponse(entity.id, entity.sku, entity.name, entity.price, entity.stock, entity.active);
System.out.println("Request : " + request); System.out.println("Entity : " + entity); System.out.println("Response: " + response); }}Request : CreateProductRequest[sku=BK-CLEAN, name=Clean Code, price=499.00, costPrice=310.00, stock=30]
Entity : Product{id=9, sku=BK-CLEAN, name=Clean Code, price=499.00, costPrice=310.00, stock=30, active=true, createdAt=2026-10-16T11:30, updatedAt=2026-10-16T11:30}
Response: ProductResponse[id=9, sku=BK-CLEAN, name=Clean Code, price=499.00, stock=30, isActive=true]What this code does
- The request has no
idand no timestamps: the client cannot know or set them. The entity has all nine fields. The response dropscostPriceand both timestamps. activeon the entity becomesisActivein the response, the name the ShopLite contract uses. The record component decides the JSON name.- The fixed
createdAtkeeps the output the same on every run; a real repository would use the current time.
In ShopLite the entities are classes (they change over time) and the DTOs are records (they are built once and sent): a request DTO for what a client sends, a response DTO for what it receives. Converting one into the other is called mapping.
One object cannot do both jobs well. The row needs fields a buyer must never see, and a request must not carry fields a client may not set, such as id.
Internal fields leak out, and leak in
Mass assignment is a client setting fields it should not: the controller takes the stored entity as the request body, so every field the client sends is stored.
Here is a controller that returns and accepts the entity directly. Watch what a client sees and what a client can change.
Example 2 · LabProduct.java, LeakyProductController.java
Runs in: the layer-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.mapping;
import java.math.BigDecimal;import java.time.LocalDateTime;
public class LabProduct {
private Long id; private String sku; private String name; private BigDecimal price; private BigDecimal costPrice; private int stock; private boolean active; private LocalDateTime createdAt; private LocalDateTime updatedAt;
public LabProduct() { }
public LabProduct(Long id, String sku, String name, BigDecimal price, BigDecimal costPrice, int stock, boolean active, LocalDateTime createdAt) { this.id = id; this.sku = sku; this.name = name; this.price = price; this.costPrice = costPrice; this.stock = stock; this.active = active; this.createdAt = createdAt; this.updatedAt = createdAt; }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getCostPrice() { return costPrice; } public void setCostPrice(BigDecimal costPrice) { this.costPrice = costPrice; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }}
package com.shoplite.lab.mapping;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
// The mistake: the entity is the response AND the request body@RestController@RequestMapping("/lab/leaky/products")class LeakyProductController {
private final LabProductStore store;
LeakyProductController(LabProductStore store) { this.store = store; }
@GetMapping("/{id}") LabProduct get(@PathVariable Long id) { return store.findById(id).orElseThrow(); }
@PutMapping("/{id}") LabProduct replace(@PathVariable Long id, @RequestBody LabProduct body) { body.setId(id); return store.save(body); }}
// src/main/java/com/shoplite/lab/mapping/LabProductStore.java: a @Repository that keeps LabProduct// objects in a ConcurrentHashMap, seeded with MOB-RN13 (id 1) and BK-CLEAN (id 2).$ curl http://localhost:8080/lab/leaky/products/1
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00,"costPrice":15200.00,"stock":40,"active":true,"createdAt":"2026-05-01T10:00:00","updatedAt":"2026-05-01T10:00:00"}
$ curl -X PUT http://localhost:8080/lab/leaky/products/1 -H 'Content-Type: application/json' -d '{"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":18999.00,"costPrice":1.00,"stock":40,"active":true}'
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":18999.00,"costPrice":1.00,"stock":40,"active":true,"createdAt":null,"updatedAt":null}What this code does
- The GET shows the leak out:
costPrice,createdAtandupdatedAtgo to every client, and the boolean comes out as"active", notisActive. - The PUT shows the leak in: the client set
costPriceto 1.00, and because it did not send the timestamps, both are nownullin the store. - Nothing here is a typo or a crash. The code "works", which is why this mistake ships so often.
Going out, Jackson writes every getter of the entity into the JSON, so cost prices, timestamps and anything added later reach every client. A renamed field silently changes the API, and the boolean getter isActive() comes out as "active", not the isActive the ShopLite contract promises. Coming in, any field the client sends is stored, and fields it leaves out become null.
The practice project layer-lab shows both. It is a Spring Boot 4.1 project like rest-lab, with the Web MVC starter, artifact layer-lab and package com.shoplite.lab. Its LabProduct entity has a cost price and two timestamps; ShopLite's real products table has neither, and the lab adds them only to show the danger.
Mapping in the service, so entities never reach the controller
Mapping is converting one object into another, such as a request DTO into an entity or an entity into a response DTO. In ShopLite the service does the mapping, so entities never reach the controller.
Here is a service that takes a DTO, changes the stored entity and returns a DTO. The controller never sees the entity.
Example 3 · ProductResponse.java, UpdateProductRequest.java, CatalogService.java, CatalogController.java
Runs in: the layer-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.mapping;
import java.math.BigDecimal;
// The DTO: exactly the fields the API promises, nothing morepublic record ProductResponse(Long id, String sku, String name, BigDecimal price, int stock, boolean isActive) {
static ProductResponse from(LabProduct p) { return new ProductResponse(p.getId(), p.getSku(), p.getName(), p.getPrice(), p.getStock(), p.isActive()); }}
package com.shoplite.lab.mapping;
import java.math.BigDecimal;
// Only the fields a client may change: no id, no costPrice, no timestampspublic record UpdateProductRequest(String sku, String name, BigDecimal price, int stock, boolean isActive) {}
package com.shoplite.lab.mapping;
import java.time.LocalDateTime;import java.util.NoSuchElementException;
import org.springframework.stereotype.Service;
@Servicepublic class CatalogService {
private final LabProductStore store;
CatalogService(LabProductStore store) { this.store = store; }
public ProductResponse get(Long id) { return ProductResponse.from(load(id)); }
public ProductResponse replace(Long id, UpdateProductRequest request) { LabProduct product = load(id); product.setSku(request.sku()); product.setName(request.name()); product.setPrice(request.price()); product.setStock(request.stock()); product.setActive(request.isActive()); product.setUpdatedAt(LocalDateTime.now()); return ProductResponse.from(store.save(product)); }
private LabProduct load(Long id) { return store.findById(id).orElseThrow(() -> new NoSuchElementException("Product " + id + " was not found.")); }}
package com.shoplite.lab.mapping;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
// The controller sees only DTOs: it never touches LabProduct@RestController@RequestMapping("/lab/products")class CatalogController {
private final CatalogService service;
CatalogController(CatalogService service) { this.service = service; }
@GetMapping("/{id}") ProductResponse get(@PathVariable Long id) { return service.get(id); }
@PutMapping("/{id}") ProductResponse replace(@PathVariable Long id, @RequestBody UpdateProductRequest request) { return service.replace(id, request); }}$ curl http://localhost:8080/lab/products/1
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00,"stock":40,"isActive":true}
$ curl -X PUT http://localhost:8080/lab/products/1 -H 'Content-Type: application/json' -d '{"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":18999.00,"stock":40,"isActive":true,"costPrice":1.00,"id":99}'
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":18999.00,"stock":40,"isActive":true}
$ curl http://localhost:8080/lab/leaky/products/1
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":18999.00,"costPrice":15200.00,"stock":40,"active":true,"createdAt":"2026-05-01T10:00:00","updatedAt":"2026-10-16T10:56:06.9150672"}What this code does
- The controller sees only
ProductResponseandUpdateProductRequest.CatalogServiceloads the entity, copies in the five fields a client may change, setsupdatedAtitself and maps back. - The PUT sends
costPriceandidanyway. They are not inUpdateProductRequest, so they never reach the entity: the last call (the leaky endpoint, used here only to look at the stored row) still showscostPrice15200.00 and the originalcreatedAt. - Your
updatedAtwill differ: it is the time you ran the PUT.
The rule in ShopLite: the service takes DTOs and returns DTOs. Mapping there, not in the controller, matters because the service is the boundary every caller uses. A startup runner or another feature also gets a ProductResponse, so none of them depend on the entity's internals.
For updates, the service loads the stored entity and copies in only the fields a client may change. Everything else, such as costPrice and createdAt, keeps its stored value.
Predict the output
Extra fields in a PUT
A client sends this PUT body. What happens to costPrice and id?
The service takes an UpdateProductRequest. What does it receive?
costPrice and id below are simply dropped. The ShopLite contract wants such a body refused with 400; the Exception Handling module switches that on.A static from() factory vs a small ProductMapper class
A static factory is a static method that builds an object, such as ProductResponse.from(product). On a record it is the shortest mapper: one method that builds the DTO from the entity.
Here are the two mapping styles side by side, then ShopLite's own ProductMapper.
Example 4 · A static from() factory and a mapper class side by side
import java.math.BigDecimal;
class Product { private final Long id; private final String sku; private final String name; private final Long categoryId; private final BigDecimal price;
Product(Long id, String sku, String name, Long categoryId, BigDecimal price) { this.id = id; this.sku = sku; this.name = name; this.categoryId = categoryId; this.price = price; }
Long getId() { return id; } String getSku() { return sku; } String getName() { return name; } Long getCategoryId() { return categoryId; } BigDecimal getPrice() { return price; }}
record CreateProductRequest(String sku, String name, Long categoryId, BigDecimal price) {}
// Style 1: a static factory on the response recordrecord ProductSummary(Long id, String name, BigDecimal price) { static ProductSummary from(Product p) { return new ProductSummary(p.getId(), p.getName(), p.getPrice()); }}
record ProductResponse(Long id, String sku, String name, Long categoryId, String categoryName, BigDecimal price) {}
// Style 2: one mapper class for both directions, with room for extra datafinal class ProductMapper { private ProductMapper() { }
static Product toNewProduct(CreateProductRequest r) { return new Product(null, r.sku(), r.name(), r.categoryId(), r.price()); // no id yet }
static ProductResponse toResponse(Product p, String categoryName) { return new ProductResponse(p.getId(), p.getSku(), p.getName(), p.getCategoryId(), categoryName, p.getPrice()); }}
public class MapperStylesDemo { public static void main(String[] args) { Product saved = new Product(6L, "ACC-AD141", "boAt Airdopes 141", 4L, new BigDecimal("1299.00"));
System.out.println("from(): " + ProductSummary.from(saved)); System.out.println("mapper: " + ProductMapper.toResponse(saved, "Accessories"));
CreateProductRequest request = new CreateProductRequest("ACC-KB100", "Wireless Keyboard", 4L, new BigDecimal("999.00")); Product fresh = ProductMapper.toNewProduct(request); System.out.println("request -> entity: id=" + fresh.getId() + ", sku=" + fresh.getSku() + ", categoryId=" + fresh.getCategoryId()); }}from(): ProductSummary[id=6, name=boAt Airdopes 141, price=1299.00] mapper: ProductResponse[id=6, sku=ACC-AD141, name=boAt Airdopes 141, categoryId=4, categoryName=Accessories, price=1299.00] request -> entity: id=null, sku=ACC-KB100, categoryId=4
What this code does
ProductSummary.from(saved)needs nothing but the entity, so a static factory on the record is enough.ProductMapper.toResponse(saved, "Accessories")takes the category name as an extra argument, which the entity cannot provide. The same class also maps a request into a new entity with no id yet.
Example 5 · src/main/java/com/shoplite/product/ProductMapper.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import java.math.BigDecimal;import java.math.RoundingMode;
/** Converts between the Product entity and the product DTOs. No rules, no storage. */final class ProductMapper {
private ProductMapper() { }
static Product toNewProduct(CreateProductRequest request) { int stock = request.stock() == null ? 0 : request.stock(); boolean active = request.isActive() == null || request.isActive(); return new Product(null, request.sku(), request.name(), request.categoryId(), money(request.price()), stock, active); }
static void copyInto(UpdateProductRequest request, Product product) { product.setSku(request.sku()); product.setName(request.name()); product.setCategoryId(request.categoryId()); product.setPrice(money(request.price())); product.setStock(request.stock()); product.setActive(request.isActive()); }
static ProductResponse toResponse(Product product, String categoryName) { return new ProductResponse(product.getId(), product.getSku(), product.getName(), product.getCategoryId(), categoryName, product.getPrice(), product.getStock(), product.isActive()); }
/** Rupees always with two decimals: 999 becomes 999.00. */ private static BigDecimal money(BigDecimal amount) { return amount.setScale(2, RoundingMode.HALF_UP); }}$ curl -X PUT http://localhost:8080/api/v1/products/6 -H 'Content-Type: application/json' -d '{"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"price":1199,"stock":120,"isActive":true}'
{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1199.00,"stock":120,"isActive":true}What this code does
- Three directions:
toNewProduct(request to new entity, with the contract defaults stock 0 and active true),copyInto(PUT request into the stored entity) andtoResponse(entity plus category name to response). moneykeeps every price at two decimals, so the PUT above sends1199and the response says1199.00, as the contract requires.- The class is
final, has a private constructor and no fields: it holds no state, so it is safe to use from every request at once.
A static factory works well when the response needs only the entity's own fields. A mapper class keeps every conversion of one feature in one place: request to new entity, request into an existing entity, entity to response. It can also take extra data the entity does not have, such as categoryName, and it can be package-private, so the entity stays hidden.
ShopLite uses ProductMapper because its response needs a category name and it maps in three directions. Both styles are plain code: no library is needed, and the compiler checks every field.
Mapping lists and pages with streams
A batched lookup is one call that fetches the data for many items together, instead of one call per item. Collect the ids first, look them all up once, then map.
Here are two ways to map a page of products: one lookup per item, and one batched lookup.
private List<ProductResponse> toResponses(List<Product> products) { Set<Long> categoryIds = products.stream().map(Product::getCategoryId).collect(Collectors.toSet()); Map<Long, String> names = categoryService.findNames(categoryIds); // one call for the page return products.stream() .map(p -> ProductMapper.toResponse(p, names.get(p.getCategoryId()))) .toList();}Example 6 · One lookup per item vs one batched lookup
import java.math.BigDecimal;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;
record Product(Long id, String name, Long categoryId, BigDecimal price) {}
record ProductResponse(Long id, String name, String categoryName, BigDecimal price) {}
// Stands in for CategoryService; each call would be one database query laterclass CategoryLookup { private static final Map<Long, String> NAMES = Map.of(2L, "Mobiles", 4L, "Accessories", 5L, "Books"); int calls = 0;
String findName(Long id) { calls++; return NAMES.get(id); }
Map<Long, String> findNames(Collection<Long> ids) { calls++; return ids.stream().collect(Collectors.toMap(id -> id, NAMES::get)); }}
public class ListMappingDemo { public static void main(String[] args) { List<Product> page = List.of( new Product(1L, "Redmi Note 13 5G", 2L, new BigDecimal("17999.00")), new Product(2L, "Samsung Galaxy M35", 2L, new BigDecimal("19999.00")), new Product(6L, "boAt Airdopes 141", 4L, new BigDecimal("1299.00")), new Product(7L, "Mi Power Bank 20000mAh", 4L, new BigDecimal("2199.00")), new Product(9L, "Clean Code", 5L, new BigDecimal("499.00")));
// One lookup per product: easy to write, slow later (5 queries for 5 rows) CategoryLookup slow = new CategoryLookup(); List<ProductResponse> first = page.stream() .map(p -> new ProductResponse(p.id(), p.name(), slow.findName(p.categoryId()), p.price())) .toList(); System.out.println("One lookup per product: " + slow.calls + " lookups");
// One batched lookup for the whole page CategoryLookup fast = new CategoryLookup(); Set<Long> categoryIds = page.stream().map(Product::categoryId).collect(Collectors.toSet()); Map<Long, String> names = fast.findNames(categoryIds); List<ProductResponse> second = page.stream() .map(p -> new ProductResponse(p.id(), p.name(), names.get(p.categoryId()), p.price())) .toList(); System.out.println("One batched lookup: " + fast.calls + " lookup");
System.out.println("Same result? " + first.equals(second)); second.forEach(System.out::println); }}One lookup per product: 5 lookups One batched lookup: 1 lookup Same result? true ProductResponse[id=1, name=Redmi Note 13 5G, categoryName=Mobiles, price=17999.00] ProductResponse[id=2, name=Samsung Galaxy M35, categoryName=Mobiles, price=19999.00] ProductResponse[id=6, name=boAt Airdopes 141, categoryName=Accessories, price=1299.00] ProductResponse[id=7, name=Mi Power Bank 20000mAh, categoryName=Accessories, price=2199.00] ProductResponse[id=9, name=Clean Code, categoryName=Books, price=499.00]
What this code does
- Both versions build the same list. The first asks for a category name inside
map, so 5 products cost 5 lookups; the second collects the ids into aSetand asks once. - The
Setalso removes repeats: the page has three categories, so the batched call asks for 3 names, not 5. - With MySQL each lookup becomes a query, so the gap grows with the page size. This is the "N+1 queries" problem, covered fully in the JPA section.
A list mapping is one stream().map(...).toList() over the entities, and a page maps the same way: map the content, keep page, size and the totals.
The trap is extra data per item. Asking for the category name inside map makes one lookup per product: 20 products, 20 lookups, which become 20 database queries later. The snippet above collects the ids first and asks once.
Next step
Check your understanding
12 quick questions