【问题标题】:Hibernate criteria for compare SUM of three columns againts another column将三列的总和与另一列进行比较的休眠条件
【发布时间】:2013-05-09 09:34:42
【问题描述】:

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

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

【问题讨论】:

    标签: hibernate criteria criteria-api


    【解决方案1】:

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

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多