crazy_rudy
crazy_rudy

Reputation: 533

Hibernate call function with criteria

i'm new to hibernate.
I want to call my custom function with criteria.
Simply, i want to call function like this :
SELECT * FROM table WHERE test=1 ORDER BY my_own_function(arg1, arg2) asc
This problem may be solved by using HQL.
But i have many optional conditions, so i have to append conditions dynamically.
Is there anyway to solve this problem? if not, could you tell me other ways?

Upvotes: 0

Views: 1544

Answers (1)

Stony
Stony

Reputation: 3624

As the comment only support a line, I paster my solutions here, 1. extend Order, the link is extend Order

package ro.tremend.util.hibernate;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;

/**
 * Extends {@link org.hibernate.criterion.Order} to allow ordering by an SQL formula      passed by the user.
 * Is simply appends the <code>sqlFormula</code> passed by the user to the resulting SQL query, without any verification.
 * @author Sorin Postelnicu
 * @since Jun 10, 2008
 */
  public class OrderBySqlFormula extends Order {
private String sqlFormula;

/**
 * Constructor for Order.
 * @param sqlFormula an SQL formula that will be appended to the resulting SQL query
 */
protected OrderBySqlFormula(String sqlFormula) {
    super(sqlFormula, true);
    this.sqlFormula = sqlFormula;
}

public String toString() {
    return sqlFormula;
}

public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    return sqlFormula;
}

/**
 * Custom order
 *
 * @param sqlFormula an SQL formula that will be appended to the resulting SQL query
 * @return Order
 */
public static Order sqlFormula(String sqlFormula) {
    return new OrderBySqlFormula(sqlFormula);
}

}

  1. use formula to add a column to order Use formula

Upvotes: 1

Related Questions