Hibernate criterion absolute value in query

1.1k views Asked by At

So I'm trying to figure out how to use absolute value in my query and I'm not having much luck. Does anyone know how it should be written? Here's what I have so far. (A Unit test)

The first option is a work around, where I basically OR both values. The second half of the unit test I'm trying to get the function to work but obviously I'm not understanding projections correctly. Any experts out there? Gavin?

public void testAbsoluteValueInHibernateCriterion() throws Exception {
        Criteria subCriteria =  ((ActionDAOImpl)getTargetObject(actionDAO, ActionDAOImpl.class)).getSessionFactory().getCurrentSession().createCriteria(Account.class);
        subCriteria.add(Restrictions.or(Restrictions.eq("currentBalance", 20.00), Restrictions.eq("currentBalance", -20.00)));
        subCriteria.list();

        subCriteria =  ((ActionDAOImpl)getTargetObject(actionDAO, ActionDAOImpl.class)).getSessionFactory().getCurrentSession().createCriteria(Account.class);
        subCriteria.setProjection(Projections.sqlProjection("abs(current_balance)",new String[] {"currentBalance"}, new Type[]{new IntegerType()}));
        subCriteria.add(Restrictions.eq("currentBalance", 20.00));
        subCriteria.list();
    }

    protected <T> T getTargetObject(Object proxy, Class<T> targetClass) throws Exception {
        if (AopUtils.isJdkDynamicProxy(proxy)) {
            return (T) ((Advised)proxy).getTargetSource().getTarget();
        } else {
            return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
        }
    }

The second method is just a helper method since I have the annotated object in Spring and am loading it up it helps me get to the root session.

The meat of my question lies in the testAbsoluteValueInHibernateCriterion method.

As far as the table goes it's pretty much : account with a current_balance field.

1

There are 1 answers

0
Uncle Iroh On

Well this is the best I've found so far:

subCriteria.add(Restrictions.sqlRestriction("abs(current_balance) = " + 20.00));

What I don't like about it is that it unties the hibernate object mapping with the propery, but it's not the worst.