我刚接触冬眠
我想用标准来调用我的自定义函数
简单地说,我想调用这样的函数:
SELECT * FROM table WHERE test=1 ORDER BY my_own_function(arg1, arg2) asc
使用HQL可以解决这个问题
但我有许多可选条件,所以我必须动态附加条件。
反正有没有解决这个问题?如果没有,你能告诉我其他方法吗?
答案 0 :(得分:1)
由于评论只支持一条线,我在这里贴出我的解决方案, 1.延长订单,链接为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);
}
}