Here is a sample code of the method I was using.

@Getter
@Setter
@AllArgsConstructor
public class MyDTO {
    private List<EntityA> listA;
    private List<EntityB> listB;
}

@RepositoryRestController
public class MyController {
    @Autowired
    private EntityARepository repositoryA;
    @Autowired
    private EntityBRepository repositoryB;

    @RequestMapping(method = RequestMethod.GET, value = "/getDTO")
    public MyDTO getDTO() {
        return new MyDTO(repositoryA.findAll(), repositoryB.findAll());
    }

}

@RepositoryRestResource
public interface EntityARepository extends JpaRepository<EntityA, Long> {}

@RepositoryRestResource
public interface EntityBRepository extends JpaRepository<EntityB, Long> {}

In other words, I want to put all two tables in the collection.

This is the response I expect.

{
    "listA" : [{.../* all EntityA */}],
    "listB" : [{.../* all EntityB */}]
}

I am currently doing two selects in this way, and I think it is not a good idea.

I would like to find a way to select once using JPA style.

1 Answers

0
Jan Mares On Best Solutions

JPA lets you create objects through new and a constructor.

SELECT new MyDTO(o.prop1, o.prop2) FROM Object o

See JPQL documentation for constructor expression:

https://docs.oracle.com/html/E13946_04/ejb3_langref.html#ejb3_langref_constructor

Spring Data JPA approach:

Class-based Projections (DTOs) https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.dtos