13

Example query in JPQL looks like this:

SELECT c FROM Customer c;

I read JPA specification, books and I can't find what this c means. In SQL we simply write:

SELECT * FROM customer;

I know we can use this c as alias i.e. in WHERE clause like this:

SELECT c FROM Customer c WHERE c.name = ...

but I still don't understand what this c actually is, how to call it (alias? object?) and why it has to be just after SELECT instead of *.

swch
  • 1,432
  • 4
  • 21
  • 37

1 Answers1

16

SQL returns rows, and rows contain columns.

JPQL is a bit more complex: it can return rows of columns, but also entity instances.

So, suppose you have an (invalid) JPQL query like

select * from School school
join school.students student
where ...

What should the query return? Instances of School? Instances of Student? columns? Quite hard to know. Suppose it returns all the fields of school and students, what would be the order of the fields? How could you use the results?

Whereas if you do

select school from School school
join school.students student
where ...

you tell JPQL that you want to get instances of the School entity.

If you do

select student from School school
join school.students student
where ...

you tell JPQL that you want to get instances of the Student entity.

If you do

select school.name, student.firstName, student.age 
from School school
join school.students student
where ...

you tell JPQL that you want to get rows, containing three columns: the school name, the student first name, and the student age.

Note that, even in SQL, it's considered bad practice to use select * from a program as well: the query probably returns more columns than really needed, you don't now the order of the columns, and you rely on the name the columns have in the result set rather than specifying the desired names in the query.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Hmm I think I understand all of that and I know that "*" should not be used but I still don't know what is school in "select school from School school". Can I say that it is an alias, or object or it has no definition? – swch Jan 11 '16 at 18:14
  • 2
    Yes, it is an alias. The exact term used by the spec, if I'm not mistaken, is " identification variable". Note that you can also write it `select school from School AS school`. – JB Nizet Jan 11 '16 at 18:20