Search code examples
javahibernatejpaswaggerswagger-codegen

Mapping between Swagger OpenAPI model and JPA entity


I am trying to map openAPI model(Generated using Swagger codegen) and JPA Entity(Generated from database schema in Hibernate) in my java REST-API, so that I can save received model into database using JPA(hibernate) entity and use model to create response for fetching data from database.

I know I can create use model and entity separately and create a mechanism to convert from one to another. However, if there is any change in database or field in model I need to update both model and entity which is cumbersome.

Is there any way to define model/entity such that it can be used in both Swagger and hibernate JPA? and does not required to create both of them(which is redundant)


Solution

  • After some research I found out the concept of DTO(Data Transfer Object) which can be mapped to your Model per your response to API call.

    You can used ModelMapper or create a custom mapper to perform the conversion from Model to DTO.

    you can use following package in spring boot(Gradle) for ModelMapper :

    implementation 'org.modelmapper:modelmapper:2.3.0'