Generating reports in JPA

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Previously we have seen about various clauses in JPQL. As of now we have been selecting only the entities through JPQL. But What if we want to retrieve multiple fields from multiple entities which do not correspond to a single java object? We will see how to generate reports in jpa in this article.

Reports in JPA:

Continuing with our data model used in previous articles, there is a relationship between Teacher and Phone entity as below.

JPA Inner joins

Now if we wanted to select Teacher entites, we could have simply written a query like

but this will return entities of type Teacher and we want only firstname and lastname of teacher and number and type of Phone.

For that we will have to write a query as follows.

This query doesn’t return an entity. The results can be retrieved and accessed using the code below.

Let us understand this code

  • SELECT t.firstName, t.lastName, p.number, p.type We are simply interested in selecting firstname,lastname from Teacher, number and type of Phone entity.
  • FROM Teacher t, Phone p defining identification variables.
  • WHERE p.teacher = t We want to select numbers for teachers.
  • List<Object[]> results = query.getResultList(); This method returns a List of Object array which contains the report data we want. This is one way we can generate reports in jpa.
  • Object[] arr = results.get(i);Retrieve individual Object[] so that it can be iterated in inner for loop.

Execute this code and you’ll get the results as follows.

Prasad Kharkar 98474643454 home
Prasad Kharkar 453454353 office
Pranil Gilda 98494395 home
Pranil Gilda 4534545353 office

Using above code, we have generated reports in jpa. I hope this article helped understand how reports in jpa can be created.

References for further study :

 

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

2 thoughts on “Generating reports in JPA

Leave a Reply

Your email address will not be published. Required fields are marked *