views:

334

answers:

1

I've made my entity classes Adress, Road and County. A Road is in a County and an Adress in on a Road. I would like to list all the Adresses in a County. Therefore, in my AdressService I say:

public List<Adress> AllAdresses(County county) {
  Adress adress = new Adress();
  Road road = new Road();
  road.setCounty(county);
  adress.setRoad(road);

  Example example = Example.create(adress);
  return (List<Adress>) adressDAO.query(Adress.class, example);
}

In my AdressDAO I have query():

public List query(Class<?> c, Example example) {
  return getSession().createCriteria(c).add(example).setMaxResults(100).list();
}

This executes the following query on my database server:

select this_.AdressId as AdressId2_0_, 
       this_.Description as Descript3_2_0_, 
       this_.DescriptionShort as Descript4_2_0_, 
       this_.HouseLetter as HouseLetter2_0_, 
       this_.HouseNr as HouseNr2_0_, 
       this_.RoadId as RoadId2_0_ 
from tblAdress this_ 
where (this_.HouseNr=0) 
limit 100

I had expected it to at least include SOME information about my entity County, and an inner join with tblRoad. tblRoad has a primary key roadId, so I expected this_.roadId to be joined with tblRoad.roadId, and I expected tblRoad.countyId to be set to the primary key of County, that is countyId.

Why is the query in this example not built correctly when I use my own entity types? If I only use integers and strings, they work fine, but not entities. How do I make joins like this work with my own entities?

+2  A: 

From the Hibernate docs:

Version properties, identifiers and associations are ignored

And that, as they say, is that.

skaffman
I seemed to have read that somewhere, but I didn't quite believe that. Isn't there something I can do about it? Specifying something about depth or what association path to go or something?
niklassaers
Query-By-Example is a bit of a toy. If you need programmatic query construction, you should really be using the full Criteria API (which is what QBE uses under the covers, in a very limited way).
skaffman
Aha, thank you very much for the tip. I'll dig back into the Hibernate Reference Documentation and learn about that. I thought that query by example was the way to go, it looks so generic and good. :-)
niklassaers
Super, I took your advice and the correct query now seems to be:return adressDAO.getSession().createCriteria(Adress.class).createCriteria("road").add(Restrictions.eq("county", county)).setMaxResults(100).list();
niklassaers