views:

193

answers:

3

Suppose I have the following objects (one table per object) with this relations: A -> B -> C -> D

If I findById an instance of A, all B, C and D are returned which is not I want. Is this possible to force Hibernate only to return A (or only it's primitive properties)?

I know that I can write "SELECT a.x, a.y, a.z, ... FROM A" and then manually put the result list of objects in A, but this is somewhat timely as I should manually fill all properties. I have also checked all Hibernate query hints but nothing related.

Mohsen

+1  A: 

select a from A a ?

also, how have you've mapped your relations? lazy="proxy" and fetch="join"?

Viktor Klang
setting lazy="proxy" and fetch="join" is global and affects all other queries. This is a single query requirement.
Mohsen
Use criteria API if you want to specify query custom fetchmodes.
Viktor Klang
+1  A: 

You can specify fetch="select" and lazy="true" in your mapping. Especially if your relations -> are lists.

bertolami
I have object to object relation (no list: one to one or many to one, where A is many side). setting lazy or fetch is global and affects all other queries. This is a single query requirement.
Mohsen
if you use the criteria api you can specify the fetch type. I don't know how/if you can do this with hql.
bertolami
+2  A: 

If you have a constructor for A which fills all fields except the ones you don't want to join, you could select like this:

SELECT NEW A(a.x, a.y, a.z) FROM A a
Bob
is this Hibernate specific feature or JPA's?
Mohsen
This is a feature of JPA.
Bob
Thanks for your help, but this way I should add a new constructor for each query which is a nightmare.
Mohsen
You can create one constructor with all fields, and fill the unwanted fields with NULL.
Bob