Dynamic query for multiple properties using Hibernate

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

Model

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

Pointand Shape- an object that may contain 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 figures is a circle.

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

My first idea was unattainable and ineffective. It consists in executing queries on all the primitive properties and then merging the results.

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

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

thank

+3
source share
1 answer

Have you looked at the query criteria ? This is a Hibernate feature for programmatically developing queries and parameters.

If you intend to request objects that meet all these conditions:

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

, -

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();

Criteria , HQL - / ..

+2

Source: https://habr.com/ru/post/1759238/


All Articles