Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package nb.db;
import java.util.Iterator;
import java.util.List;
import org.apache.cayenne.access.translator.batch.BatchTranslator;
import org.apache.cayenne.access.translator.batch.DefaultBatchTranslatorFactory;
import org.apache.cayenne.access.translator.batch.UpdateBatchTranslator;
import org.apache.cayenne.dba.DbAdapter;
import org.apache.cayenne.dba.QuotingStrategy;
import org.apache.cayenne.map.DbAttribute;
import org.apache.cayenne.query.UpdateBatchQuery;
public class NBBatchTranslatorFactory extends DefaultBatchTranslatorFactory {
@Override
protected BatchTranslator updateTranslator( UpdateBatchQuery query, DbAdapter adapter, String trimFunction ) {
return new NBUpdateBatchTranslator( query, adapter, trimFunction );
}
public class NBUpdateBatchTranslator extends UpdateBatchTranslator {
public NBUpdateBatchTranslator( UpdateBatchQuery query, DbAdapter adapter, String trimFunction ) {
super( query, adapter, trimFunction );
}
@Override
protected String createSql() {
UpdateBatchQuery updateBatch = (UpdateBatchQuery)query;
QuotingStrategy strategy = adapter.getQuotingStrategy();
List<DbAttribute> qualifierAttributes = updateBatch.getQualifierAttributes();
List<DbAttribute> updatedDbAttributes = updateBatch.getUpdatedAttributes();
StringBuilder buffer = new StringBuilder( "UPDATE " );
buffer.append( strategy.quotedFullyQualifiedName( query.getDbEntity() ) );
buffer.append( " SET " );
int len = updatedDbAttributes.size();
for( int i = 0; i < len; i++ ) {
if( i > 0 ) {
buffer.append( ", " );
}
DbAttribute attribute = updatedDbAttributes.get( i );
buffer.append( strategy.quotedName( attribute ) );
if( attribute.getName().equals( "company" ) ) {
buffer.append( " = COALESCE( ?, " + attribute.getName() + " )" );
}
else {
buffer.append( " = ?" );
}
}
buffer.append( " WHERE " );
Iterator<DbAttribute> i = qualifierAttributes.iterator();
while( i.hasNext() ) {
DbAttribute attribute = i.next();
appendDbAttribute( buffer, attribute );
buffer.append( updateBatch.isNull( attribute ) ? " IS NULL" : " = ?" );
if( i.hasNext() ) {
buffer.append( " AND " );
}
}
return buffer.toString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment