简体   繁体   English

Java:JPQL选择语句

[英]Java: JPQL select statement

select x from X x where xaid = :a_id --> Always 0 objects selected select x from X x where xaid = :a_id >始终选择0个对象

Why does the above JPQL statement not work, but the one below work? 为什么上面的JPQL语句不起作用,而下面的那一个却起作用?

select a from A a where a.id = :a_id --> a_obj select a from A a where a.id = :a_id a_id-> a_obj
select x from X x where xa = :a_obj --> Always correct number of objects selected select x from X x where xa = :a_obj >总是正确选择对象的数量

Neither query throws an exception during execution, but a different number of results are obtained. 在执行过程中,两个查询都不会引发异常,但是会获得不同数量的结果。

Thanks 谢谢


Update 更新资料

I tried the following queries by using joins: 我通过使用联接尝试了以下查询:
select x from X x, xa a where xaid = :a_id --> TopLink exception for unexpected token select x from X x, xa a where xaid = :a_id >用于意外令牌的TopLink异常

and this: select x from X x JOIN xa a where a.id = :a_id --> Always correct number of objects selected 然后select x from X x JOIN xa a where a.id = :a_id >始终正确选择对象的数量

With the latter query, I have solved the initial problem at hand. 通过后一个查询,我已经解决了手头的最初问题。 However, now I have got two queries which should work, but for some reason don't. 但是,现在我有两个查询应该可以工作,但是由于某种原因没有。

select x from X x where xaid = :a_id --> Always 0 objects selected select x from X x where xaid = :a_id >始终选择0个对象
select x from X x, xa a where xaid = :a_id --> TopLink exception for unexpected token select x from X x, xa a where xaid = :a_id >用于意外令牌的TopLink异常

Has anyone else encountered similar behaviour? 还有其他人遇到过类似的行为吗?

With the following entity for X 对于X具有以下实体

@Entity
public class EntityX {

    @Id @GeneratedValue
    private Long id;

    @OneToOne
    private EntityA a;

    // ...
}

And this one for A: 这是A的:

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

   //...
}

The following JPQL query: 以下JPQL查询:

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

Generates the following SQL: 生成以下SQL:

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

It simply works and returns as many results as expected. 它简单地工作并返回预期的结果。

Tested with Hibernate (and EclipseLink). 经过Hibernate(和EclipseLink)测试。 If this is not representative of your case, please add more details. 如果这不能代表您的情况,请添加更多详细信息。

I think you have to also bring in entity a in the first example so that it's attributes are visible. 我认为您还必须在第一个示例中引入实体a,以便其属性可见。

Something like 就像是

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

(I don't use JPA, I stick to HQL, so this is untested, unproven and comes without a money-back guarantee.) (我不使用JPA,我坚持使用HQL,因此这未经测试,未经验证且没有退款保证。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM