7

I need to retrieve items based on a few different restrictions, one is to have code of 234 the other is to have calculated number of less than 10, but I am not sure how to pass values to the sqlRestrictions method.

I am using {alias} but it passes Item rather than city to this.

List<Store> stores = (List<Store>) sessionFactory.getCurrentSession()
                .createCriteria(Item.class)
                .createAlias("Address", "address")
                .createAlias("address.myJoinTable.city", "city")
                .setProjection(pl)
                .add(Restrictions.eq("address.myJoinTable.city",
                        session.load(City.class, myId)))
                .add(Restrictions
                        .sqlRestriction("SELECT (
                                                 {alias}.id * {alias}.code * " 
                                                 + mynumber1 + " * " + mynumber2 + ") 
                                                  as number from city 
                                                  HAVING number < 10")
                .setResultTransformer(
                        new AliasToBeanResultTransformer(Store.class))
                .list();
Daniel Newtown
  • 2,873
  • 8
  • 30
  • 64

1 Answers1

9

You can use public static Criterion sqlRestriction(String sql, Object value, Type type) if you only need to pass one value. Use public static Criterion sqlRestriction(String sql, Object[] values, Type[] types) for multiple values.

For example:

Type[] tipos = {IntegerType.INSTANCE, IntegerType.INSTANCE};
Integer[] values = {1, 2};

criteria.add(Restrictions.sqlRestriction("SELECT ({alias}.id * {alias}.code * ? * ?) AS number FROM city HAVING number < 10", values, tipos ));
walen
  • 7,103
  • 2
  • 37
  • 58
Paula Toro
  • 91
  • 4