Why “SELECT c” instead of “SELECT * ” in JPQL?

爷,独闯天下 提交于 2019-12-06 02:20:31

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!