Merge POJO and Entity

Asked

Viewed 55 times

1

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

    @Entity
    public class Employee {

         @Id
         private Integer id;       
         ...
    }

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

I imagined an approach where serializo in json format an abstract class that is implemented by the entity, would be a good approach?

1 answer

0


Has better approaches yes.

First, the entities are responsible for mapping their tables in the database. Making them also assume 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 (putting one more piece of information or hiding another), you will have to control it within Entity, making it much more complex and confusing, probably full of JPA and Json library Annotations.

The ideal is not to serialize your entities unless they traffic through some kind of remote interface (using remote EJB, for example). Since this is a rare case, don’t worry about it.

The solution is to leave the entities with their responsibility: map the tables and bring information about them. If you want to present 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 (like Modelmapper) to transfer the information from the entity to Dto.

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

This will separate responsibilities and give you the power to change the Json return by changing only Dto, without worrying about the impacts on (or the) Entity within your application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.