Dewprism
Dewprism

Reputation: 11

JPA join statement logic

Help this noob programmer. I've been using JPA, but there seems to be something bothering me with it's logic using the join statement.

For example, I have an entity named Person, with fields name, age, gender. And then for example in a query,

select p from Person p join p.gender g

Note: This is just an example why I'm confused.

The question is, why would you join p (person) and p.gender? what's the point? What results can it give?

Upvotes: 0

Views: 117

Answers (1)

Ondrej Bozek
Ondrej Bozek

Reputation: 11501

The point is in joining multivalued relationships. There is no point in joining on p.gender, I'm expecting p.gender to be attribute or single valued relationship (person can have only one gender).

But if you have joined on multivalued attribute e.g. Collection<Order> orders (person can have multiple orders), then you can search for persons which have some specific orders:

select p from Person p join p.orders o where o.price > 12000

This query will find all Persons which have some order with price higher than 12000. You can't do it without join :

select p from Person p where p.orders.price > 12000

This won't work because orders is multivalued and you can't traverse it like this. You have to use join (or something else e.g. subquery).

Upvotes: 1

Related Questions