Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Spring Entity objects to modified JSON Object

I am having a few tables in my DB. Employee, Address, Phone_id

Table Employee
====================
ID | Emp_Name | Address_id | Phones_id

Table Address
====================
ID | Block_no | City | State

Table Phone_id
====================
ID | Phone_1 | Phone_2 | Phone_3

When I display the JSON received directly from repository, it works, but not in the format expected by UI. I wish to make some changes to the received JSON. Basically, transform it and then provide response over REST.

So my questions are:

  1. Is there any Spring way to solve my requirement. So that I can just map my entity class to some JSON class.

  2. Is there any design pattern that can be used in such a scenario.

Thanks a bunch!

like image 623
Abhay Dandekar Avatar asked Feb 15 '18 13:02

Abhay Dandekar


1 Answers

It is advisable to keep you @Entity classes and your JSON representation classes separated.

Let's say you have @Entity class Employee. One option is to use the same Employee class to describe your database entity (using let's say JPA annotations) and then use the same Employee class to describe the JSON you want to return to the client (using let's say Jackson annotations).

That's considered bad practice for various reasons. Most common one is that most of the time you don't want all your entities to be mapped 1:1 to your JSON response.

In order to deal with this, a common approach is to create a separate Employee class to describe your JSON representation. You can call it EmployeeDto.

Then you have to write a custom logic that maps @Entity Employee to EmployeeDto.

You can use static factory method like so:

//Persistence layer class
@Entity
public class Employee {
  @Id
  @GeneratedValue
  @Column(name = "id")
  private Long id;

  @Column(name = "first_name")
  private String firstName;

  @Column(name = "last_name")
  private String lastName;

  //getters/setters
}

//REST layer class
public class EmployeeDto {
  @JsonProperty("first_name")
  private String firstName;
  @JsonProperty("last_name")
  private String lastName;

  public EmployeeDto() {}

  // you can do any transforamtion/validation here
  public static EmployeeDto fromEntity(Employee employee){
    EmployeeDto dto = new EmployeeDto();
    dto.setFirstName(employee.getFirstName);
    dto.setLastName(employee.getLastName);
  }

  //getters/setters
}

Then your controller will return List<EmployeeDto> instead of @Entity Employee.

UPDATE:

Spring doesn't provide automatic conversion mechanism between DTO and Entity object. I think it depends on the complexity of the classes and number of pairs (DTO/Entity), but most of the time it's easy enough to implement the conversion yourself.

Of course there are libraries out there, which provide some level of automation with the mapping:

  • ModelMapper
  • Orica
like image 52
hovanessyan Avatar answered Nov 06 '22 05:11

hovanessyan