0

我有一个表,其列为 ID、col1、col2、col3、col4、col5。我想添加一个休眠条件限制为(col1 + col2 + col3) < col4

所有这些列都包含整数值。我怎样才能达到这个要求?任何帮助表示赞赏。

4

1 回答 1

0

我发现这可以通过编写自定义标准来实现。以下是与他人分享的示例代码,

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();
    }
}
于 2013-05-15T03:15:58.593 回答