Spring JPA CriteriaBuilder,联接表上的where子句

时间:2018-12-06 14:21:56

标签: spring jpa

如何在联接表上创建带有多个where子句的查询?

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery(A.class);
Root<A> a = cq.from(A.class);
ListJoin<A, B> b = a.joinList("bs");
cq.select(a).where(cb.equal(b.get(B_.usDotNumber), 3), 
cb.equal(a.get(A_.accountNumber), 1));
List<A> as = em.createQuery(cq).getResultList();

我得到的错误是:

java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: accountNumber of: com.foo.B [select generatedAlias0 from com.foo.A as generatedAlias0 inner join generatedAlias0.bs as generatedAlias0 where ( generatedAlias0.accountNumber=1 ) and ( generatedAlias0.usDotNumber=3 )]
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)

...

生成的查询:

select generatedAlias0 from com.foo.A as generatedAlias0 inner join generatedAlias0.bs as generatedAlias0 where ( generatedAlias0.accountNumber=1 ) and ( generatedAlias0.usDotNumber=3 );

为什么两个表都使用“ generateAlias0”,我该如何解决?查询应为:

select generatedAlias0 from com.foo.A as generatedAlias0 inner join generatedAlias0.bs as generatedAlias1 where ( generatedAlias0.accountNumber=1 ) and ( generatedAlias1.usDotNumber=3 );

编辑:根据要求添加实体关系。删除了所有多余的东西。

@Entity
public class A {
    @Column(name = "FOO")
    private String accountNumber;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "anId", referencedColumnName = "anotherId", updatable = false)
    @LazyCollection(LazyCollectionOption.FALSE)
    private final List<B> bs = Collections.synchronizedList(new ArrayList<>());
}

@Entity
public class B {
    @Column(name = "BAR")
    private Integer usDotNumber;
}

非常感谢!

1 个答案:

答案 0 :(得分:0)

此查询在删除select(a)之后起作用。不,我听不懂,但也许会帮助别人。

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery(A.class);
Root<A> a = cq.from(A.class);
ListJoin<A, B> b = a.joinList("bs");
cq.where(cb.equal(b.get(B_.usDotNumber), 3), cb.equal(a.get(A_.accountNumber), 1));
List<A> as = em.createQuery(cq).getResultList();