Java criteria restrictions sum of columns lower than value

这一生的挚爱 提交于 2019-12-13 07:04:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!