【问题标题】:Spring Data JPA check if object exits where elementcollecion is equal to listSpring Data JPA检查是否存在元素集合等于列表的对象
【发布时间】:2019-01-16 23:15:14
【问题描述】:

我创建了包含另一个表的 id 的元素集合

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "participantchatchannel", joinColumns = 
@JoinColumn(name = "channelId"))
@Column(name = "participantId")
private List<Long> participantsIdList;

我可以看到该列表包含我希望它包含的值。现在我想检查是否有一个对象包含与我提供的完全相同的 ID。

我曾尝试像这样扩展 CrudRepository:

boolean existsByParticipantsIdListEquals(List<Long> participantIdList);

但我不断收到错误:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ','.

我做错了什么以及为什么(可能我不太明白由此生成的 sql 是什么)。

编辑:

启用日志后,我可以在控制台中看到以下行:

2018-08-10 07:27:14.997 DEBUG 8880 --- [nio-8080-exec-2] org.hibernate.SQL                        : select TOP(?) chatchanne0_.id as col_0_0_ from chatchannel chatchanne0_ left outer join participantchatchannel participan1_ on chatchanne0_.id=participan1_.channel_id where participan1_.participant_id=(? , ?)
2018-08-10 07:27:15.001 TRACE 8880 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [BIGINT] - [2]
2018-08-10 07:27:15.002 TRACE 8880 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [BIGINT] - [3]
2018-08-10 07:27:15.005  WARN 8880 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 102, SQLState: S0001
2018-08-10 07:27:15.005 ERROR 8880 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : Incorrect syntax near ','.

【问题讨论】:

  • 能否请您发布导致错误的SQL语句?
  • @SimonMartinelli 我用堆栈跟踪更新了问题

标签: java spring-boot spring-data-jpa jpql


【解决方案1】:

您的方法签名错误。您不能将 Equals 与集合一起用作参数。 这就是 Hibernate 生成无效 where 子句的原因:

where participan1_.participant_id=(? , ?)

你必须使用 In。所以你的查询应该是这样的:

boolean existsByParticipantsIdListIn(List<Long> participantIdList);

【讨论】:

  • 嗯,它不太好用。我有 [2,3] 和 [2,4] 并且两者都返回 true。
  • 你能把Hibernate生成的SQL贴出来吗?
猜你喜欢
  • 2018-07-02
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 2010-11-23
  • 1970-01-01
相关资源
最近更新 更多