views:

256

answers:

2

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

Has anyone else encountered similar behaviour?

A: 

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

mdma
You clearly don't have to.
Pascal Thivent
@Pascal - Agreed. I wouldn't have expected it to be necessary either, knowing Hibernate. I'm just pushing for another datapoint to see if we can get TopLink to deliver what's expected.
mdma
:%s/don't/shouldn't/g
Pascal Thivent
@Pascal - thanks for the clarification of what you sed - that's gentler wording.
mdma
+1  A: 

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.

Pascal Thivent
@Pascal Thivent : Thanks for the answer, you have indeed understood my question correctly, however, I am puzzled by the different result I am getting. Could you please point me in the direction of how to see what SQL is generated, like what you have done? (I'm using Toplink/Java DB on Glassfish 2.1.1, with Netbeans IDE, if it makes a difference)
bguiz
I don't use TopLink but I think that the `toplink.logging.level.sql` property should do the trick. Have a look at [TopLink JPA Extensions for Logging](http://www.oracle.com/technology/products/ias/toplink/JPA/essentials/toplink-jpa-extensions.html#TopLinkLogging) for details.
Pascal Thivent