如果是列表,如何检查JPA查询参数的长度?

发布于 2025-01-21 04:40:07 字数 716 浏览 0 评论 0原文

 @Query("Select DISTINCT answer from Answer answer " +
        "WHERE ( answer.user = :user or (:user is null)) " +
        "AND ( answer.quiz in :quizzes or (:quizzes is null))"
)
public Page<Answer> multiParam(Quiz[] quizzes, User user, Pageable pageable);

只要提供测验,该查询就可以工作。

但是用户是可选的。

问题是,当测验参数丢失时,null检查将在此错误中失败:

org.springframework.dao.InvalidDataAccessApiUsageException: Encountered array-valued parameter binding, but was expecting [com.quiz.models.Quiz (n/a)]; nested exception is java.lang.IllegalArgumentException: Encountered array-valued parameter binding, but was expecting [com.quiz.models.Quiz (n/a)

我想找到一种使测验参数作为可选的方法。

 @Query("Select DISTINCT answer from Answer answer " +
        "WHERE ( answer.user = :user or (:user is null)) " +
        "AND ( answer.quiz in :quizzes or (:quizzes is null))"
)
public Page<Answer> multiParam(Quiz[] quizzes, User user, Pageable pageable);

This query works as long as quizzes is provided.

User however is optional.

The problem is that when quizzes the parameter is missing, the is null check will fail with this error:

org.springframework.dao.InvalidDataAccessApiUsageException: Encountered array-valued parameter binding, but was expecting [com.quiz.models.Quiz (n/a)]; nested exception is java.lang.IllegalArgumentException: Encountered array-valued parameter binding, but was expecting [com.quiz.models.Quiz (n/a)

I want to find a way to make Quizzes the parameter as optional.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一场春暖 2025-01-28 04:40:07

尝试以下内容:

 @Query("Select DISTINCT answer from Answer answer " +
        "WHERE ( answer.user = :user or (:user is null)) " +
        "AND (COALASCE(:quizzes,null) IS NULL OR answer.quiz in :quizzes))"
public Page<Answer> multiParam(List<Quiz> quizzes, User user, Pageable pageable);

Coalasce返回第一个非零值,在这种情况下,在测验为null时将返回NULL。

不确定这是否适用于数组类型。

JPA的本机解决方案仍在等待: https://github.com /spring-projects/spring-data-jpa/essugn/622

Try the following :

 @Query("Select DISTINCT answer from Answer answer " +
        "WHERE ( answer.user = :user or (:user is null)) " +
        "AND (COALASCE(:quizzes,null) IS NULL OR answer.quiz in :quizzes))"
public Page<Answer> multiParam(List<Quiz> quizzes, User user, Pageable pageable);

COALASCE returns the first non null value , which in this case would return null when quizzes is null.

Not sure if this would work with Array type or not.

A native solution from JPA is still pending : https://github.com/spring-projects/spring-data-jpa/issues/622

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文