开发者

Java: JPQL select statement

select x from X x where x.a.id = :a_id --> Always 0 objects selected

Why does the above JPQL statement not work, but the one below work?

select a from A a where a.id = :a_id --> a_obj

select x from X x where x.a = :a_obj --> Always correct number of objects selected

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, x.a a where x.a.id = :a_id --> TopLink exception for unexpected token

and this: select x from X x JOIN x.a a where a.id = :a_id --> Always correct number of objects selected

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 x.a.id = :a_id --> Always 0 objects selected

select x from X x, x.a a whe开发者_如何学运维re x.a.id = :a_id --> TopLink exception for unexpected token

Has anyone else encountered similar behaviour?


With the following entity for X

@Entity
public class EntityX {

    @Id @GeneratedValue
    private Long id;

    @OneToOne
    private EntityA a;

    // ...
}

And this one for A:

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

   //...
}

The following JPQL query:

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

Generates the following 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). 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.

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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜