Reputation: 533
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
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);
}
}
Upvotes: 1