为什么"SELECT c"而不是"SELECT *"在JPQL中? [英] Why "SELECT c" instead of "SELECT * " in JPQL?

查看:259
本文介绍了为什么"SELECT c"而不是"SELECT *"在JPQL中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JPQL中的示例查询如下:

Example query in JPQL looks like this:

SELECT c FROM Customer c;

我阅读了JPA规范,书籍,但找不到c的含义.在SQL中,我们只需编写:

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

SELECT * FROM customer;

我知道我们可以将此c用作别名,即在WHERE子句中这样使用:

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

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

但是我仍然不明白这个c实际上是什么,如何调用它(别名?对象?),以及为什么它必须在SELECT之后而不是*.

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 *.

推荐答案

SQL返回行,并且行包含列.

SQL returns rows, and rows contain columns.

JPQL稍微复杂一点:它可以返回列的行,还可以返回实体实例.

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

因此,假设您有一个(无效的)JPQL查询,例如

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?

如果可以的话

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

您告诉JPQL您要获取School实体的实例.

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

如果您这样做

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

您告诉JPQL您想要获取Student实体的实例.

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

如果您这样做

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

您告诉JPQL您想要获取包含三列的行:学校名称,学生名字和学生年龄.

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

请注意,即使在SQL中,也要从程序中使用select *被认为是不好的做法:查询返回的列可能比实际需要的要多,您现在不需要列的顺序,而您依赖列在结果集中具有的名称,而不是在查询中指定所需的名称.

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.

这篇关于为什么"SELECT c"而不是"SELECT *"在JPQL中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆