Avoid exposing JPA entities in REST API, Instead generate client beans using OpenAPI Generator and map them to entities using MapStruct.

Ravinder Thirumala
4 min readApr 15, 2020

There’s always been discussion about whether we should expose JPA entities in RESTful APIs, or define Data Transfer Objects(DTOs) and map entity classes to the DTOs. We will discuss pros and cons of exposing JPA entities as REST API resources.

We will see how to generate REST API DTOs from Open API Specification using openapi-generator tools and also how to greatly simplify mapping between JPA entities and DTOs using MapStruct code generator.

Why it is tempting to expose entities as REST API resources

  1. Most times entities look the same as RESTful DTO, exposing JPA entities directly reduces code, Controllers, services, and repositories all deal with the same classes.
  2. Reduce code and maintenance overhead of two classes, like when adding an attribute one and forget to add in another.

Why its not good idea to expose JPA entities as REST API resources

  1. Separation of concerns, resource representation concerns of REST shoul be separate from the transactional concerns of JPA. Which means API and persistence layer should evolve independently of each other.
  2. There could be mismatches between internal representation and the API resource. Like a resource having…

--

--