EntityManager Query Question

prain
prain used Ask the Experts™
on
I am learing JPA queries...

In a query like this....

Query q = em.createQuery("Select p from Person p where p.personName = John");

What is p ?

is p a place holder for a column name?

Why is it says Person p - I am confused with that
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
p is an alias for the table Person, but the query looks wrong to me, I would've expected the following:
Query q = em.createQuery("Select p.* from Person p where p.personName = 'John'");
My opinion, if there is only one table in the query then don't use an alias:
Query q = em.createQuery("Select * from Person where personName = 'John'");

Author

Commented:
So what's point of the alias even we have multiple tables involved?
mccarlIT Business Systems Analyst / Software Developer
Top Expert 2015
Commented:
@John_Vidmar,

Note that the author is talking about JPA queries not SQL queries, and so the syntax is different.


@prain,

The 'p' is called an "identification variable" in JPA terminology. It is similar to an alias in SQL (as mentioned above by John) so that when it is referred to in the select clause it is known 'which' entity you want returned (as the query may reference multiple entity types/tables) and when referred to in the where clause it is known which entity to look up the 'personName' attribute on.

As you say, in this case, there is only one entity type/table so it seems redundant to have to name the reference to the Person entity as 'p' but (unlike in SQL) it is a requirement of the java persistence query language to have these 'identifiers' / 'aliases'

Author

Commented:
so when you say (using above example) p.personName I belive p referes to an object (or an entity). If so personName is the property defined in the Person class. Is that correct?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial