java - 使用 JPQL 计算关联对象的正确方法

标签 java hibernate orm jpa jpql

编写此 JPA 查询的正确方法是什么?我只是在猜测,因为我无法解决或无法在我的 JPA 书中找到它。

Query query=em.createQuery("select m from Meeting m where count(m.attendees) = 0");
return query.getResultList();

我目前正在使用 Hibernate 尝试此操作,但出现 mysql 错误!

ERROR org.hibernate.util.JDBCExceptionReporter - You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near ')=0' at line 1

最佳答案

要严格回答问题的标题,使用SIZE:

Query query=em.createQuery("select m from Meeting m where size(m.attendees) = 0");
return query.getResultList();

来自 JPA 规范:

4.6.16.2 Arithmetic Functions

functions_returning_numerics::=
ABS(simple_arithmetic_expression) |
SQRT(simple_arithmetic_expression) |
MOD(simple_arithmetic_expression, simple_arithmetic_expression) |
SIZE(collection_valued_path_expression)

The ABS function takes a numeric argument and returns a number (integer, float, or double) of the same type as the argument to the function.

The SQRT function takes a numeric argument and returns a double.

The MOD function takes two integer arguments and returns an integer.

The SIZE function returns an integer value, the number of elements of the collection. If the collection is empty, the SIZE function evaluates to zero.

Numeric arguments to these functions may correspond to the numeric Java object types as well as the primitive numeric types.

0 的特殊情况下,您还可以使用 IS EMPTY

4.6.11 Empty Collection Comparison Expressions

The syntax for the use of the comparison operator IS EMPTY in an empty_collection_comparison_expression is as follows:

collection_valued_path_expression IS [NOT] EMPTY

This expression tests whether or not the collection designated by the collection-valued path expression is empty (i.e, has no elements).

Example:

SELECT o
FROM Order o
WHERE o.lineItems IS EMPTY

If the value of the collection-valued path expression in an empty collection comparison expression is unknown, the value of the empty comparison expression is unknown.

我会同时测试两者,看看哪个最有效(检查查询计划)。

关于java - 使用 JPQL 计算关联对象的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3509408/

相关文章:

java - 如何在多线程环境下mysql hibernate使用一张表的自增值插入多张表

java - 像 hibernate 这样的 ORM 框架在迭代结果集时是否实现任何类型的行映射器?

java - 我缺少哪些 Hibernate 注释?

java - 如何在 spring 中将集合对象绑定(bind)到 Controller

java - 使用 Spark SQL 数据集作为基于 RDD 的作业

java - 多对多关系未保存

java - 如何更新具有 OneToMany 关联的对象的子行

Windows 上带有通配符的 java 类路径 : Requires semi-colon at the end

java - 在java中创建数组对象

java - Hibernate EHCache 程序的问题