通过JPA 2.0 CriteriaBuilder加入两个JPA实体时,别名无效 [英] Invalid alias when joining two JPA entities via JPA 2.0 CriteriaBuilder

查看:610
本文介绍了通过JPA 2.0 CriteriaBuilder加入两个JPA实体时,别名无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个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:

  1. 定义查询的根,因为join方法只能应用于RootJoin类型的实例:

  1. Define the root of the query because the join method can only be applied either to an instance of Root or Join 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆