标签:
在Criteria查询中
List cats = sess.createCriteria(Cat.class) .add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING) ).list();
直接拿着官方的代码试了下,报错,点进去看了看源代码,如下
/** * Create a restriction expressed in SQL with one JDBC parameter. Any occurrences of <tt>{alias}</tt> will be * replaced by the table alias. * * @param sql The SQL restriction * @param value The parameter value * @param type The parameter type * * @return The Criterion * * @see SQLCriterion */ public static Criterion sqlRestriction(String sql, Object value, Type type) { return new SQLCriterion( sql, value, type ); }
第一个是参数String类型,是SQL语句的条件部分,第二个参数是参数值,第三个参数是类型
根据案例和源代码,可以推断出{alias}.name中{alias}是表的别名,我用的是user表,于是根据理解,这样写了下,如下
Criteria criteria = session.createCriteria(User.class); criteria.add(Restrictions.sqlRestriction(“lower({User}.name ) LIKE lower(?)", "cater%", Hibernate.STRING));
结果还是报错,把Hibernate设置成自动打印出sql语句后,sql如下
Hibernate: select this_.id as id0_0_, this_.age as age0_0_, this_.birth as birth0_0_, this_.name as name0_0_ from user this_ where lower(this_).name like lower(?)
可以看到lower也被打印了出来,而且Hibernate会自动给别起别名,所以下面的形式,别名也对应不上
{User}.name LIKE ?
于是抱着试一试的态度,改成了这样:
Criteria criteria = session.createCriteria(User.class); criteria.add(Restrictions.sqlRestriction(“{alias}.name LIKE lower(?)", "cater%", Hibernate.STRING));
这次对了,打印的sql为
Hibernate: select this_.id as id0_0_, this_.age as age0_0_, this_.birth as birth0_0_, this_.name as name0_0_ from user this_ where this_.name like ?
看来那里还必须写成{alias},那alias究竟是什么意思呢?是别名的意思,我的理解是,hibernate把{alias}当成了通配符
标签:
原文地址:http://www.cnblogs.com/liuconglin/p/5686766.html