use of org.qi4j.entitystore.sql.internal.SQLEntityState in project qi4j-sdk by Qi4j.
the class SQLEntityStoreMixin method applyChanges.
@Override
public StateCommitter applyChanges(final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> states) {
return new StateCommitter() {
@Override
public void commit() {
Connection connection = null;
PreparedStatement insertPS = null;
PreparedStatement updatePS = null;
PreparedStatement removePS = null;
try {
connection = database.getConnection();
connection.setAutoCommit(false);
insertPS = database.prepareInsertEntityStatement(connection);
updatePS = database.prepareUpdateEntityStatement(connection);
removePS = database.prepareRemoveEntityStatement(connection);
for (EntityState state : states) {
EntityStatus status = state.status();
DefaultEntityState defState = ((SQLEntityState) state).getDefaultEntityState();
Long entityPK = ((SQLEntityState) state).getEntityPK();
if (EntityStatus.REMOVED.equals(status)) {
database.populateRemoveEntityStatement(removePS, entityPK, state.identity());
removePS.addBatch();
} else {
StringWriter writer = new StringWriter();
writeEntityState(defState, writer, unitofwork.identity());
writer.flush();
if (EntityStatus.UPDATED.equals(status)) {
Long entityOptimisticLock = ((SQLEntityState) state).getEntityOptimisticLock();
database.populateUpdateEntityStatement(updatePS, entityPK, entityOptimisticLock, defState.identity(), writer.toString(), unitofwork.currentTime());
updatePS.addBatch();
} else if (EntityStatus.NEW.equals(status)) {
database.populateInsertEntityStatement(insertPS, defState.identity(), writer.toString(), unitofwork.currentTime());
insertPS.addBatch();
}
}
}
removePS.executeBatch();
insertPS.executeBatch();
updatePS.executeBatch();
connection.commit();
} catch (SQLException sqle) {
SQLUtil.rollbackQuietly(connection);
if (LOGGER.isDebugEnabled()) {
StringWriter sb = new StringWriter();
sb.append("SQLException during commit, logging nested exceptions before throwing EntityStoreException:\n");
SQLException e = sqle;
while (e != null) {
e.printStackTrace(new PrintWriter(sb, true));
e = e.getNextException();
}
LOGGER.debug(sb.toString());
}
throw new EntityStoreException(sqle);
} catch (RuntimeException re) {
SQLUtil.rollbackQuietly(connection);
throw new EntityStoreException(re);
} finally {
SQLUtil.closeQuietly(insertPS);
SQLUtil.closeQuietly(updatePS);
SQLUtil.closeQuietly(removePS);
SQLUtil.closeQuietly(connection);
}
}
@Override
public void cancel() {
}
};
}
Aggregations