Merge POJO and Entity

1

I'm studying JPA and need to serialize an entity:

    @Entity
    public class Employee {

         @Id
         private Integer id;       
         ...
    }

Is it good practice to serialize an entity directly just like I do with a POJO? Or do you have better approaches?

I thought of an approach where I serialize in json format an abstract class that is implemented by the entity, would it be a good approach?

    
asked by anonymous 13.09.2018 / 02:08

1 answer

0

It has better approaches, yes.

First, it is the responsibility of the entities to map their tables to the database. To make them also take the part of representing the information in JSON format seems to hurt the SRP Single Responsability Principle ).

If you need some flexibility in the information to be displayed in this Json (put one more information or hide another), you will have to control this within the entity, making it much more complex and confusing, probably full of JPA annotations and the Json library.

Ideally, you should not serialize your entities unless they travel by some kind of remote interface (using remote EJB for example). Since this is a rare case, do not worry about it.

The solution is to leave the entities responsible for them: map the tables and bring information from them. If you want to display their information in a Json, create some kind of Dto (even if it is identical to the entity):

class EmployeeDto implements Serializable {
    private Integer id;
}

And use some mapper tool (such as ModelMapper) to transfer the entity information to the Dto.

EmployeeDto dto = modelMapper.map(employeeEntity, EmployeeDto.class);

This will leave the responsibilities separate and give you the power to change Json's return by changing only the Dto, without worrying about the impacts on the entity within your application.

    
13.09.2018 / 02:57