微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 使用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

06001

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:

06002

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

Example:

06003

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.

我会测试两者以确定哪一个是最有效的(检查查询计划).

原文地址:https://www.jb51.cc/java/129849.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐