ajile81 wrote:
I think you simply want to look at .setMaxResults(int maxResults).
I use a rather complex query, and the criteria will change dynamically based on the args I pass into my method; I reserve the sort order and max results for the tail end.
AJ
Thanks, but that doesn't solve the problem: adding a limit to a plain-jane count(*) query will not work as the query only returns 1 result - the result of the count. It will not stop the database from counting up to the limit, hence my subselect above.
I have a sort of dirty workaround with a custom postgres (my database) dialect:
Code:
public class CustomPostgreSQLDialect extends PostgreSQLDialect {
@Override
public String getLimitString(String sql, boolean hasOffset) {
// check if this is a count query
if (sql != null && sql.toLowerCase().startsWith("select count(*) as y0_")) {
// replace count(*) with *
String newSql = sql.substring("select count(*) as y0_".length());
newSql = "select *" + newSql;
// and rewrite as a subquery
newSql = "select count(*) as y0_ from (" + newSql + " limit ?" ;
if (hasOffset) newSql += " offset ?";
newSql += ") as ___tmpResult";
return newSql;
} else {
// regular query, delegate to superclass
return super.getLimitString(sql, hasOffset);
}
}
}