Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value to sqlRestriction of hibernate?

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();
like image 538
Daniel Newtown Avatar asked Apr 07 '15 02:04

Daniel Newtown


Video Answer


1 Answers

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 ));
like image 146
Paula Toro Avatar answered Sep 29 '22 02:09

Paula Toro