Proper use of Entity AND DTO to provide Json in a Restful web service

There are many articles that DTO is not required with JPA / hibernate

Use an open session as a template or a disciplined build phase to avoid raw data problems. Hibernate frees the developer from writing tedious data transfer objects (DTOs) ... The above lines are taken from https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/best-practices.html

Also in an article by a member of SO Bohzo I read DTO, rarely required

Even articles against exhibiting objects say that there is no need to have a DTO if Entities have no behavior (when they are POJOs), as in an anemic area model

Suppose Entity Class Exists

class Department{
    List<Employee> employees //lazily loaded collection 

Each item in the collection contains another lazy collection.

 class Employee{
    List<Account> accounts

There is a getDepartment () method that is used by a calm service to provide information to the Json department.

Possible solutions:

Solution 1) According to the hibernation documentation, opening and closing a hibernation session for each request (that is, the topmost method in the controller is transactional?) Or better using Spring OpenSessionInViewFilter in accordance with this SO post

, ? JPA/hibernate?

2) , , , . ? API getDepartment API DAO?

3) DTO DTO, persistence , . API getDepartmentOnly() getDepartmentWithEmployees() , , 100% API , DTO

4) bohzo , .

2 , ?

+4
1

Hibernate :

public Department getDepartmentWithEmployees(Long departmentId) {
   Department result = em.find(Department.class, departmentId);
   Hibernate.initialize(result.getEmployees());
   return result;
}

:

public Department getDepartmentWithEmployees(Long departmentId) {
   String query = "select d from Department d join fetch d.employees where d.id = :departmentId";
   ...
}

...

, , ( API- ).

JPA/Hibernate; ( JDBC).

+3

Source: https://habr.com/ru/post/1598621/


All Articles