views:

91

answers:

1

I'm working on creating a Hibernate query engine that can create dynamic queries. Thus far I've been using the Criterion API to generate the queries. I'm having a hard time writing the engine in an OO fashion. I want to be able to create a new class for each association and have it pass back a fragment of the SQL call.

For example:

A person might own a home, a car, and a boat.

I want the user to be able to search "Return any person that has a blue home and a red boat" I have a searchTerm Map that looks like:

home.color = blue

boat.color = red

I'd want one singleton, for each criteria (boat,car,home), that I can pass in the entire map and it returns to me a Criteria object that I can use to build up my query. That's the theory. The problem I'm having is, in Hibernate, I need to create a criteria or alias to make associations between person and boat/house/car. In order to do that, I have to pass in the hibernate session. What I really want is to be able to return a detached-criteria and merge them all together. But it doesn't seem to be a way to do that.

In summary: A class that returns a criteria object that makes associations without the session object.

Any thoughts?

Thanks for reading!

+3  A: 

And DetachedCriteria doesn't work for you because?

Update (based on comment)

How do I have different objects create different Detached Criteria and merge them all together in one query?

You don't "merge" them. In your example Person is the root entity (because you're searching for users; plus it has associations to all other entities like House, Boat, Car). Thus, you'll be initially creating criteria for Person:

DetachedCriteria personCriteria = DetachedCriteria.forClass(Person.class);

and then, based on your conditions, create an association when needed:

// this assumes that "Boat" is mapped as many-to-one "boat" property on "Person"
DetachedCriteria boatCriteria = personCriteria.createCriteria("boat");
boatCriteria.add(Restriction.eq("color", "red"));

// same for house
DetachedCriteria houseCriteria = personCriteria.createCriteria("house");
houseCriteria.add(Restriction.eq("color", "blue"));

// when you're all done you search based on "personCriteria"
personCriteria.getExecutableCriteria(session).list();


On a side note, you might want to take a look at Hibernate Generic DAO project, particularly its Search component which is basically Criteria API done right :-)

ChssPly76
+1 for mentioning the interesting google project.
BalusC
But how do I have different objects create different Detached Criteria and merge them all together in one query?
davidemm