tags:

views:

50

answers:

1

Hello

I have a model that has several properties. The properties can be primitive (String) or complex (Object). The user can make a query on each primitive property. I would like to know if there is an easy way to build dynamically the query. I use Java and Hibernate.

The model

public class Model {
  String prop1;
  Point prop2;
  List<Shape> prop3;
}

Point and Shape are object that can contains primitives or objects. An example of a query would be all instances where prop1 = "A" and the coordinates are x = 3 and y = 8 and one of the shape is a circle.

prop1 = "A" and prop2.x = 3 and prop2.y and prop3.get(i).type = "Circle"; we would have to iterate on all instances of prop3.

My first idea was unmaintainable and inefficient. It consists in doing queries on all the primitive properties and then merge the results.

  • Get all instances where prop1 = "A"
  • Get all instances where prop2.x = 3 and prop3 = y;
  • Get all instances where one of the Shape.type = "Circle";
  • Get the intersection of all 3 sets

Is there any existing library or algorithm that can solve this problem in a better (smarter) way?

Thanks

+1  A: 

Have you looked at Criteria queries? It's a Hibernate feature for constructing queries and parameters programmatically.

If your intent is to query for entities that match all of these conditions:

prop1 = "A" and prop2.x = 3 and prop2.y and prop3.get(i).type = "Circle"

with support for association queries, then you could do something like

Criteria criteria = session.createCriteria(Model.class);
criteria.add(Restrictions.eq("prop1", "A"));
criteria.createCriteria("prop2")
    .add(Restrictions.eq("x", 3));
    .add(Restrictions.eq("y", 2));
criteria.createCriteria("prop3").add(Restrictions.in("type", "Circle"));

List results = criteria.list();

The real strength in Criteria queries is building the query in code rather than in a HQL string - allows you to dynamically add/set properties, etc.

matt b
of course you could write the same query that I have here in HQL (with INs, JOINs, etc).
matt b