MySQL 如何将值传递给休眠的sqlRestriction?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29482880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:05:27  来源:igfitidea点击:

How to pass value to sqlRestriction of hibernate?

mysqlhibernatehibernate-criteria

提问by Daniel Newtown

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.

我需要根据一些不同的限制来检索项目,一种是代码为 234,另一种是计算出的数量小于 10,但我不确定如何将值传递给 sqlRestrictions 方法。

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

我正在使用 {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();

回答by Paula Toro

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.

如果只需要传递一个值,则可以使用 public static Criterion sqlRestriction(String sql, Object value, Type type)。对多个值使用公共静态Criterion sqlRestriction(String sql, Object[] values, Type[] types)

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