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

public class MyDTO {
    private List<EntityA> listA;
    private List<EntityB> listB;

public class MyController {
    private EntityARepository repositoryA;
    private EntityBRepository repositoryB;

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


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

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

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:

Spring Data JPA approach:

Class-based Projections (DTOs)