U
U
UNy2019-05-27 01:09:20
Java
UNy, 2019-05-27 01:09:20

How to execute a Join query in Hibernate/Spring Data?

What if the information I want to show lies in several tables? How to make a join request in Hibernate or for example Spring Data Jpa? I found an example of this code:

EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
  
List<Object[]> results = em.createQuery("SELECT p.firstName, p.lastName, n.phoneNumber FROM Person p, PhoneBookEntry n WHERE p.firstName = n.firstName AND p.lastName = n.lastName").getResultList();

for (Object[] result : results) {
  log.info(result[0] + " " + result[1] + " - " + result[2]);
}

em.getTransaction().commit();
em.close();

A list of Object arrays and getting by index looks strange to say the least :) What other options are there? I read about DTO, it looks logical, but the question arises: if the application consists of a bunch of entities, will there be a lot of DTO too?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2019-05-27
@UNy

What you need is called projection https://www.baeldung.com/spring-data-jpa-projections
And, in general, yes - how many requests with different data will be, so many DTOs will need to be created - the repository you need to know what type of object to build.
Or, yes, List, since there is no other option to return untyped data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question