简体   繁体   中英

Java: JPQL select statement

select x from X x where xaid = :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 xa = :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, xa a where xaid = :a_id --> TopLink exception for unexpected token

and this: select x from X x JOIN xa 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 xaid = :a_id --> Always 0 objects selected
select x from X x, xa a where xaid = :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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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