0

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?

crazy_rudy
  • 533
  • 2
  • 4
  • 19
  • Hey, did you solve it? I have the same question. – Stony Jun 17 '14 at 06:18
  • @Stony I've solved it by using HQL, not Criteria. using Criteria, it seems there is no supported way to call my own function by hibernate. – crazy_rudy Jun 18 '14 at 02:18
  • Thanks a lot for your reply. I got 2 solutions to use Criteria; 1. extend Order; 2. user formula to add a column to order. – Stony Jun 18 '14 at 06:28

1 Answers1

1

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
Community
  • 1
  • 1
Stony
  • 3,541
  • 3
  • 17
  • 23