Created
August 12, 2015 10:28
-
-
Save hugithordarson/8a21aa4247385732a4ce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @return The number of rows matching the given expression. | |
*/ | |
public static long count( ObjectContext oc, Class<? extends DataObject> entityClass, Expression expression ) { | |
StringBuilder b = new StringBuilder(); | |
b.append( "SELECT count(a) " ); | |
b.append( " FROM " ); | |
b.append( oc.getEntityResolver().getObjEntity( entityClass ).getName() ); | |
b.append( " a" ); | |
List<Object> parameters = new ArrayList<>(); | |
if( expression != null ) { | |
b.append( " WHERE " ); | |
b.append( expression.toEJBQL( parameters, "a" ) ); | |
} | |
String queryString = b.toString(); | |
EJBQLQuery query = new EJBQLQuery( queryString ); | |
for( int i = 0; i < parameters.size(); i++ ) { | |
query.setParameter( i + 1, parameters.get( i ) ); | |
} | |
List result = oc.performQuery( query ); | |
for( Object object : result ) { | |
return (Long)object; | |
} | |
throw new IllegalStateException( "Execution should never reach here (count is returned in the above loop)" ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment