问题
I am getting sorted results using hibernate criteria which generates the below sql:
select * from mytable order by name asc;
This is how i do it with hiberante criteria:
criteria.addOrder(Order.asc("name"));
Now, i have created a function in postgres DB as: customSort(text)
and want to use with hibernate criteria such that following sql is generated:
select * from mytable order by customSort(name) asc;
How can i call this function in hibernate to make my custom sorting and generate equivalent sql?
Any code sample will help alot
Thanks, Akhi
回答1:
Use Hibernate Native SqlQuery to acheive this.
You cannot access a Database specific native functions in criterial queries.
sess.createSQLQuery("select * from mytable order by
customSort(name) asc").list();
回答2:
I have spent some time on this and found a solution by extendeding a class CustomOrder.java from Order.java and override the toString() method as below:
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException
{
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);
Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName);
StringBuffer fragment = new StringBuffer();
for (int i = 0; i < columns.length; i++)
{
SessionFactoryImplementor factory = criteriaQuery.getFactory();
fragment.append("customOrder");
fragment.append("(");
boolean lower = ignoreCase && type.sqlTypes(factory)[i] == Types.VARCHAR;
if (lower)
{
fragment.append(factory.getDialect().getLowercaseFunction())
.append('(');
}
fragment.append(columns[i]);
if (lower)
fragment.append(')');
fragment.append(")");
fragment.append(ascending ? " asc" : " desc");
if (i < columns.length - 1)
fragment.append(", ");
}
return fragment.toString();
}
then we need to call :
criteria.addOrder(CustomOrder.asc("name"));
instead of calling criteria.addOrder(Order.asc("name"))
this worked and i was able to place DB method call in where clause as
select * from mytable order by customSort(name) asc;
I am just wondering is there a similar way such that i can place this function call in select part also using criteria?? for example:
select customSort(col1), col2, col3 from mytable order by customSort(name) asc;
pelase post your suggestions.
来源:https://stackoverflow.com/questions/16460070/how-to-call-postgres-function-with-hibernate-criteria