【问题标题】:@Query giving QuerySyntaxException@Query 给出 QuerySyntaxException
【发布时间】:2021-11-24 14:51:16
【问题描述】:

我想从Communication 表中获取appointment_type_ids 列表包含Integer 的行。

Communication.java

@Getter
@Setter
@Entity
@Table(name = "communication")
public class Communication{

    @Column("id")
    private Long id;

    @Column("name")
    private String name;

    @Column("appointment_type_ids")
    private List<Integer> appointmentTypeIds;

}

CommunicationRepository.java


@Repository
public interface CommunicationRepository extends JpaRepository<Communication, Long>,
        QuerydslPredicateExecutor<Communication>, JpaSpecificationExecutor<Communication> {

    @Query("SELECT c FROM communication c WHERE ?1 = ANY(c.appointment_type_ids)")
    List<Communication> findAppointments(Integer integer);
}
 

我收到以下错误

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: c near line 1, column 56 [SELECT c FROM communication c WHERE ?1 = ANY(c.appointment_type_ids)]

我该如何解决这个问题?

【问题讨论】:

    标签: spring-boot spring-data-jpa


    【解决方案1】:

    你可以试试这个吗:

    SELECT c FROM Communication c WHERE ?1  in(c.appointment_type_ids)
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
    • 感谢您的回答!使用这个我在调用findAppointments() 时得到ERROR: operator does not exist: integer = integer[]
    • 尝试使用本机查询,如果它有效告诉我@Query(value="SELECT c FROM Communication c WHERE ?1 in(c.appointment_type_ids)",nativeQuery = true)
    【解决方案2】:

    ANY 表达式需要一个子查询,我认为您的查询需要MEMBER OF

    @Query("SELECT c FROM Communication c  WHERE ?1 MEMBER OF c.appointentTypeIds")
    

    【讨论】:

    • 再次感谢您!这编译得很好,但我必须在appointmentTypeIds 字段中添加@ElementCollection。之后,在尝试将 PUT 值与 "appointment_type_ids":[3,8], 放入表中时,我得到了回复 { "code": "UNSUPPORTED_OPERATION", "message": "The provided 3 is not a List!" }
    • @jennyjenkins 一步一步。首先,修改@QueryCommunicationRepository#findAppointments 后是否按照您的意图工作?如果是,那么您的原始问题得到了回答,您应该投票/标记为正确解决了您的问题的答案。如果您在上面的评论中有其他问题,例如 PUT 操作,那么这是一个完全不同的问题,您应该发布一个新问题,包括社区的所有必要信息来帮助您。谢谢
    • 我不知道是不是这样,因为我不知道如何处理标记为@ElementCollection 的列,所以我无法实际测试它。然而最终为我工作的是@Query(value = "SELECT * FROM communication c WHERE ?1 = ANY(c.appointment_type_ids)", nativeQuery = true) List&lt;Communication&gt; findAppointments(Integer integer);。感谢您的帮助!
    【解决方案3】:

    我认为您应该通过Communication 名称而不是communication 引用该表。所以应该是

    SELECT c FROM Communication c WHERE ?1 = ANY(c.appointment_type_ids)
    

    【讨论】:

    • 为什么,如果表名是 communication ?虽然我尝试使用Communication,但仍然有同样的例外。
    • @jennyjenkins 它是一个 JPA 查询而不是原生查询,您应该处理 Communication 的实体类。而appointment_type_ids 应该是appointmentTypeIds
    • 感谢您的回答!但即使@Query("SELECT c FROM Communication c WHERE ?1 = ANY(c.appointentTypeIds)") 也给出了相同的结果。我做错了什么?
    猜你喜欢
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    相关资源
    最近更新 更多