2010-05-24 60 views
1

select x from X x where x.a.id = :a_id - >总是选择的Java:JPQL select语句

为什么上面的JPQL语句不行0对象,但下面的工作吗?

select a from A a where a.id = :a_id - > a_obj
select x from X x where x.a = :a_obj - >总是正确的对象数选择

既不查询抛出执行期间的异常,但获得了不同数量的结果。

感谢


更新

我通过尝试使用下面的连接的查询:
select x from X x, x.a a where x.a.id = :a_id - > TopLink的例外意外的标记

这: select x from X x JOIN x.a a where a.id = :a_id - >始终选择正确的对象数量

对于后者的查询,我已经解决了最初的问题。但是,现在我有两个应该工作的查询,但由于某种原因,不。

select x from X x where x.a.id = :a_id - >总是0对象选择
select x from X x, x.a a where x.a.id = :a_id - > TopLink的意外令牌

有其他人遇到过类似的行为异常?

+0

哪个JPA提供商正在使用? – mdma 2010-05-24 23:26:29

+0

@mdma:GlassFish 2.1.1上的TopLink/Java DB – bguiz 2010-05-24 23:34:40

回答

0

我想你还必须在第一个例子中引入实体a,以便它的属性可见。

喜欢的东西

select x from X x join fetch x.a where x.a.id = :a_id 

(我不使用JPA,我坚持HQL,所以这是未经测试,未经证实的和都是有退款保证。)

+0

你显然不需要。 – 2010-05-24 23:38:43

+0

@帕斯卡尔 - 同意。知道Hibernate,我不会期望它也是必需的。我只是在推动另一个数据点,以了解我们是否可以让TopLink实现预期目标。 – mdma 2010-05-24 23:45:22

+0

:%s /不/不应该/ g – 2010-05-25 00:17:08

1

用下面的实体对于X

@Entity 
public class EntityX { 

    @Id @GeneratedValue 
    private Long id; 

    @OneToOne 
    private EntityA a; 

    // ... 
} 

而这其中对于A:

@Entity 
public class EntityA { 
    @Id @GeneratedValue 
    private Long id; 

    //... 
} 

以下JPQL查询:

from EntityX x where x.a.id = :id 

生成以下SQL:

select 
    entityx0_.id as id282_, 
    entityx0_.a_id as a2_282_ 
from 
    EntityX entityx0_ 
where 
    entityx0_.a_id=? 

它运行良好,并预期返回结果数量。

使用Hibernate(和EclipseLink)进行测试。如果这不代表您的情况,请添加更多详细信息。

+0

感谢您的回答,您的确已经正确理解我的问题,但是,我对我得到的不同结果感到困惑。请你指点一下如何看看生成了什么SQL,就像你所做的一样? (我使用的是Glassfish 2.1.1上的Toplink/Java DB,使用Netbeans IDE,如果它有所不同) – bguiz 2010-05-25 00:06:26

+0

我不使用TopLink,但我认为'toplink.logging.level.sql'属性应该执行招。有关详细信息,请查看[JPA链接日志记录链接](http://www.oracle.com/technology/products/ias/toplink/JPA/essentials/toplink-jpa-extensions.html#TopLinkLogging)。 – 2010-05-25 00:15:31