问题
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));
But it seems like the string "a+b"
is not accepted. How do I have to write my restriction?
回答1:
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
There are few possible solutions:
1st: sql restriction:
//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.
2nd: Formula:
Add to your entity a virtual column using @Formula annotation:
@org.hibernate.annotations.Formula("a + b")
private int aSumB;
and use it as a standard property:
criteria.add(Restrictions.lt("aSumB", Integer.valueOf(10));
3rd Custom Criteria:
If you are using it a lot consider to create custom criteria by implementing org.hibernate.criterion.Criterion
来源:https://stackoverflow.com/questions/11986011/java-criteria-restrictions-sum-of-columns-lower-than-value