JPA Inner Joins

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’ve seen introduction about jpa joins, in this article we will learn about JPA Inner Joins. They can be written explicitly using JOIN operator in FROM clause.

JPA Inner Joins

Some points to remember :

  • INNER keyword is optional.
  • Join can only appear in FROM clause

Syntax for JPA Inner Joins query is

As said earlier, INNER and AS keywords are optional.

JPA Inner Joins Example

Consider Teacher and Phone entities where there is ManyToOne relationship between Phone and Teacher . i.e. A Teacher can have multiple Phones. They can be represented as follows.

JPA Inner joins

If we want to retrieve the phone numbers of a teacher, the query would be as follows.

  • JOIN keyword says the JPQL consists of an INNER JOIN (as INNER keyword is optional)
  • t.phones  is a path expression that traverses phone numbers of Teacher.
  • p is the identification variable for JPA inner join specified using  t.phones  path expression.

 

Consider you have tables mapped for entities in diagram and the data is as follows.

Phone Table

idPhone number type idTeacher
6 98474643454 home 4
7 453454353 office 4
8 98494395 home 5
9 4534545353 office 5

 

Teacher Table

4 Prasad Kharkar

Now we would like to retrieve phone numbers of the teacher with firstName = "Pranil"and print it out. JPQL would be

Here we have used named parameters, execute this query using

It will print the phone numbers of Teacher with firstName=="Pranil"

I hope this example helped understand JPA Inner joins. Any improvements are most welcome 🙂

 

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.

6 thoughts on “JPA Inner Joins

  • Pingback:JPA Outer join | theJavaGeek

  • Pingback:Criteria api joins | theJavaGeek

  • January 20, 2017 at 8:56 pm
    Permalink

    Thank you for these explanations, but what about ManyToMany relationship?

    Reply
  • May 17, 2017 at 6:16 pm
    Permalink

    Please,
    can I have the phone and teacher classes?

    Reply
  • January 30, 2018 at 8:17 pm
    Permalink

    hi, I need help, because
    I have three Entities,I need all information, topics and posts are Entities with FetchType.LAZY

    SELECT c FROM Category c JOIN FETCH c.topics JOIN FETCH c.topics.posts

    It works with java 7, and jboss6.4 server, but with java 8 and jboss7,
    = query specified join fetching, but the owner of the fetched association was not present in the select list

    Reply

Leave a Reply

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