Skip to content

Instantly share code, notes, and snippets.

@hugithordarson
Created May 19, 2015 13:20
Show Gist options
  • Save hugithordarson/05de4ad2f3d6f2cdc16a to your computer and use it in GitHub Desktop.
Save hugithordarson/05de4ad2f3d6f2cdc16a to your computer and use it in GitHub Desktop.
package strimillinn.core;
import java.util.List;
import org.apache.cayenne.DataObject;
import org.apache.cayenne.DataRow;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.exp.Property;
import org.apache.cayenne.map.ObjEntity;
import org.apache.cayenne.query.SQLTemplate;
public class CayenneUtils {
/**
* @return DataRows containing distinct values of the given properties in the given entity.
*
* @param oc The ObjectContext to fetch into
* @param entityClass Class of Cayenne entity to fetch
* @param properties List of properties to fetch values for
*/
public static List<DataRow> distinctValues( ObjectContext oc, Class<? extends DataObject> entityClass, Property<?>... properties ) {
String sqlString = sqlStringForDistinctSelect( oc, entityClass, properties );
SQLTemplate query = new SQLTemplate( entityClass, sqlString );
query.setFetchingDataRows( true );
return oc.performQuery( query );
}
/**
* @return SQL string to fetch distinct values of [properties] in the given entity.
*
* @param oc The ObjectContext user to resolve the class to an entity.
* @param entityClass Class of Cayenne entity to fetch
* @param properties List of properties to fetch values for
*/
static String sqlStringForDistinctSelect( ObjectContext oc, Class<? extends DataObject> entityClass, Property<?>... properties ) {
ObjEntity entity = oc.getEntityResolver().getObjEntity( entityClass );
String dbEntityName = entity.getDbEntityName();
StringBuilder b = new StringBuilder();
b.append( "select distinct " );
for( int i = 0; i < properties.length; i++ ) {
if( i > 0 ) {
b.append( "," );
}
String attributeName = properties[i].getName();
String dbAttributeName = entity.getAttribute( attributeName ).getDbAttributeName();
b.append( dbAttributeName );
}
b.append( " from " );
b.append( dbEntityName );
String sqlString = b.toString();
return sqlString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment