如何在集合(或集合)内查询具有嵌套值的给定参数?
我有一个实体foo
,其中包含bar
s的嵌入式集合。
@Entity
@Table(name = "foo")
public class Foo {
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "bar", joinColumns = @JoinColumn(name = "foo_id"))
private Set<Bar> bars = new HashSet<>();
//...
}
@Embeddable
public class Bar {
@Column(name = "value", nullable = false)
private String value;
//...
}
我想找到所有匹配设置内部给定参数(字符串)的foo
s。
我想在jpql中实现的一些伪代码:
Foo find(String toMatch) {
return allFoos.stream()
.filter(f -> f.getBars.stream()
.map(Bar::getValue)
.anyMatch(value -> value.equals(toMatch)))
.findFirst()
.get();
}
但是,当我尝试此查询时:
@Repository
public interface FooRepository extends JpaRepository<Foo, Long> {
@Query("select f from Foo f " +
"where (" +
" :toMatch in f.bars.value " +
")")
Optional<Foo> find(@Param("toMatch") String toMatch);
}
它抛出:
由:org.hibernate.QueryException引起:非法尝试 带有元素属性参考的取消收集[foo.id.bars] [value]
我想避免使用需要加入多个表的解决方案。这是伪代码,但是实际查询中充满了大量的大型企业SQL,位置或语句。因此,加入越少。
I have an entity Foo
with an embedded collection of Bar
s.
@Entity
@Table(name = "foo")
public class Foo {
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "bar", joinColumns = @JoinColumn(name = "foo_id"))
private Set<Bar> bars = new HashSet<>();
//...
}
@Embeddable
public class Bar {
@Column(name = "value", nullable = false)
private String value;
//...
}
I'd like to find all Foo
s that match a given parameter (String) inside of the Set.
Some pseudo-code of what I want to achieve in JPQL:
Foo find(String toMatch) {
return allFoos.stream()
.filter(f -> f.getBars.stream()
.map(Bar::getValue)
.anyMatch(value -> value.equals(toMatch)))
.findFirst()
.get();
}
However when I try this query:
@Repository
public interface FooRepository extends JpaRepository<Foo, Long> {
@Query("select f from Foo f " +
"where (" +
" :toMatch in f.bars.value " +
")")
Optional<Foo> find(@Param("toMatch") String toMatch);
}
It throws:
Caused by: org.hibernate.QueryException: illegal attempt to
dereference collection [foo.id.bars] with element property reference
[value]
I'd like to avoid a solution where I need to join multiple tables. This is pseudo code, but the actual query is filled with tons of big 'ol complex enterprise SQL where or and statements. So the less joins the better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我确实相信正确的JPQL查询应该看起来像:
I do believe the correct JPQL query should look like: