您好,我有一个关于将简单的SQL语句转换为Java休眠限制的问题.
Hi I've a question about converting a simple SQL statement into a java hibernate restriction.
SQL:
SELECT a + b FROM col WHERE a + b < 10当我尝试将其转换为条件时,我得到:
When I try to convert this to a criteria I get:
Criteria criteria = createCriteria(); criteria.createAlias("col","col").add(Restrictions.lt("a+b",10));但是似乎字符串"a+b"不被接受.我该如何写我的限制?
But it seems like the string "a+b" is not accepted. How do I have to write my restriction?
推荐答案很可能是因为Hibernate试图将 a + b 解析为您实体的属性,并且您获得了
It's likely because Hibernate is trying to resolve a+b as your entity's property, and you get
org.hibernate.QueryException: could not resolve property: a+b
几乎没有解决方案:
第一个:sql限制:
//Hibernate 4.x criteria.add(Restrictions.sqlRestriction("col_a+col_b < ?", Integer.valueOf(10), org.hibernate.type.StandardBasicTypes.INTEGER); // Hibernate 3.x criteria.add(Restrictions.sqlRestriction("col_a+col_b < ?", Integer.valueOf(10), org.hibernate.Hibernate.INTEGER);有一个问题,您必须使用列名而不是属性名.
There is one issue that you must use column names instead of property names.
第二名:公式:
使用 @Formula 注释将虚拟列添加到您的实体:
Add to your entity a virtual column using @Formula annotation:
@org.hibernate.annotations.Formula("a + b") private int aSumB;并将其用作标准属性:
criteria.add(Restrictions.lt("aSumB", Integer.valueOf(10));第三个自定义条件:
如果您经常使用它,请考虑通过实现 org.hibernate.criterion.Criterion
If you are using it a lot consider to create custom criteria by implementing org.hibernate.criterion.Criterion
更多推荐
Java条件限制列总和低于值
发布评论