Hibernate 将三列之和与另一列进行比较的休眠条件
我有一个列为ID、col1、col2、col3、col4、col5的表。我想添加一个hibernate条件限制,如Hibernate 将三列之和与另一列进行比较的休眠条件,hibernate,criteria,criteria-api,Hibernate,Criteria,Criteria Api,我有一个列为ID、col1、col2、col3、col4、col5的表。我想添加一个hibernate条件限制,如(col1+col2+col3)
(col1+col2+col3)
所有这些列都包含整数值。我怎样才能达到这个要求?感谢您的帮助。我发现可以通过编写自定义标准来实现这一点。下面是要与其他人共享的示例代码
public class CostomizedExpression implements Criterion {
private final TypedValue[] NO_TYPED_VALUES = new TypedValue[0];
private String[] otherColumns;
private String column;
private String operator;
public CostomizedExpression (String operator, String column, String... otherColumns) {
this.column = column;
this.otherColumns = otherColumns;
this.operator = operator;
}
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, column);
StringBuffer buffer = new StringBuffer();
buffer.append("(");
for (int i = 0; i < otherColumns.length; i++) {
buffer.append(" ");
buffer.append(criteriaQuery.getColumnsUsingProjection(criteria, otherColumns[i])[0]);
if (i < otherColumns.length - 1) {
buffer.append("+");
}
buffer.append(" ");
}
buffer.append(" )");
buffer.append(operator);
buffer.append(" ");
buffer.append(columns[0]);
return buffer.toString();
}
@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return NO_TYPED_VALUES;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < otherColumns.length; i++) {
buffer.append(" ");
buffer.append(otherColumns[i]);
if (i < otherColumns.length - 1) {
buffer.append("+");
}
buffer.append(" ");
}
buffer.append(" ");
buffer.append(operator);
buffer.append(" ");
buffer.append(column);
return buffer.toString();
}
}
公共类CostomizedExpression实现标准{
私有最终类型值[]无类型值=新类型值[0];
私有字符串[]其他列;
私有字符串列;
私有字符串运算符;
公共CostomizedExpression(字符串运算符、字符串列、字符串…其他列){
this.column=列;
this.otherColumns=otherColumns;
this.operator=操作员;
}
@凌驾
公共字符串toSqlString(Criteria、CriteriaQuery、CriteriaQuery)引发HibernateException{
String[]columns=criteriaQuery.getColumnsUsingProjection(条件,列);
StringBuffer=新的StringBuffer();
缓冲区。追加(“”);
for(int i=0;i