通过JPA 2.0 CriteriaBuilder加入两个JPA实体时,别名无效 [英] Invalid alias when joining two JPA entities via JPA 2.0 CriteriaBuilder
问题描述
我有两个JPA实体
class A{
@OneToMany
Lis<B> entitiesB;
@Column("STATUS")
String status;// will sort based on this column
}
和
class B{
@ManyToOne
A entityA;
@Column("PROPERTY_ONE")
String propertyOne;
....
@Column("PROPERTY_M")
String propertyM;
....
}
我需要先将A与B联接起来,然后对B中的列进行过滤.我有以下条件:
I need to left join A with B and then perform filtering on columns from B. I have the following criteria:
Join<A, B>root=criteriaBuilder
.createQuery(A.class)
.from(A.class)
.join("entitiesB");
CriteriaQuery<A> query = criteriaBuilder.createQuery(A.class);
query.select(query.from(A.class).join("entitiesB"))
.distinct(true)
.where(formWhereClause(filters))
.orderBy(formOrderByClause());
如何通过A
实体的status
属性形成过滤器
How do I form the filter by the status
property from A
entity
criteriaBuilder.notEqual(root.get("A").get("status"), "SOME_STATUS_VALUE");
它为我生成了以下SQL:
It has generated me the following SQL:
select distinct generatedAlias0 from A as generatedAlias1
inner join generatedAlias1.entitiesB as generatedAlias0
where ( generatedAlias2.A.status<>:param0 ) and ( generatedAlias2.propertyOne like :param1 )
order by generatedAlias2.propertyM desc
我遇到以下异常:
'org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.ast.QuerySyntaxException:
Invalid path generatedAlias2.A.status '
我该如何解决?我正在使用Hibernate 4.3.5作为持久性提供程序.
How can I fix it? I am using Hibernate 4.3.5 as the persistence provider.
推荐答案
CriteriaQuery查询= criteriaBuilder.createQuery(A.class);
CriteriaQuery query = criteriaBuilder.createQuery(A.class);
表示您要返回类型为A
的实例.因此,您的select
子句必须指定查询根目录,而不是像Join
那样的实例:
means that you want to return instances of type A
. Therefore, your select
clause must specify query root instead of an instance of Join
as you did:
-
定义查询的根,因为
join
方法只能应用于Root
或Join
类型的实例:
Define the root of the query because the
join
method can only be applied either to an instance ofRoot
orJoin
types:
Root<A> root = query.from(A.class);
定义联接(I need to left join A with B
):
Join<A, B> b = root.join("entitiesB", JoinType.LEFT);
定义SELECT
条款:
query.select(root)
.distinct(true)
.where(formWhereClause(filters))
.orderBy(formOrderByClause());
如何通过A实体的status属性形成过滤器
How do I form the filter by the status property from A entity
形成如下:
criteriaBuilder.notEqual(root.get("status"), "SOME_STATUS_VALUE");
,如果要使用B
的属性作为过滤器,请定义它,例如:
and if you want to use attributes of B
as a filter define it, for example, as:
criteriaBuilder.equal(b.get("propertyOne"), "SOME_VALUE");
这篇关于通过JPA 2.0 CriteriaBuilder加入两个JPA实体时,别名无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!