数据库
首页 > 数据库> > mysql – 如何将值传递给hibernate的sqlRestriction?

mysql – 如何将值传递给hibernate的sqlRestriction?

作者:互联网

我需要根据一些不同的限制检索项目,一个是234的代码,另一个是计算的数量小于10,但我不知道如何将值传递给sqlRestrictions方法.

我正在使用{alias},但它将Item而不是city传递给它.

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

解决方法:

如果只需传递一个值,则可以使用public static Criterion sqlRestriction(String sql, Object value, Type type).将public static Criterion sqlRestriction(String sql, Object[] values, Type[] types)用于多个值.

例如:

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

标签:mysql,hibernate,hibernate-criteria
来源: https://codeday.me/bug/20190623/1274865.html