/**
* {@inheritDoc}
*/
public void addBean(DynaBean bean) throws DataSinkException
{
Table table = _model.getDynaClassFor(bean).getTable();
Identity origIdentity = buildIdentityFromPKs(table, bean);
if (_ensureFkOrder && (table.getForeignKeyCount() > 0))
{
WaitingObject waitingObj = new WaitingObject(bean, origIdentity);
for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
{
ForeignKey fk = table.getForeignKey(idx);
Identity fkIdentity = buildIdentityFromFK(table, fk, bean);
if ((fkIdentity != null) && !fkIdentity.equals(origIdentity))
{
Identity processedIdentity = (Identity)_identityMap.get(fkIdentity);
if (processedIdentity != null)
{
updateFKColumns(bean, fkIdentity.getForeignKeyName(), processedIdentity);
}
else
{
waitingObj.addPendingFK(fkIdentity);
}
}
}
if (waitingObj.hasPendingFKs())
{
if (_log.isDebugEnabled())
{
StringBuffer msg = new StringBuffer();
msg.append("Defering insertion of row ");
msg.append(buildIdentityFromPKs(table, bean).toString());
msg.append(" because it is waiting for:");
for (Iterator it = waitingObj.getPendingFKs(); it.hasNext();)
{
msg.append("\n ");
msg.append(it.next().toString());
}
_log.debug(msg.toString());
}
_waitingObjects.add(waitingObj);
return;
}
}
insertBeanIntoDatabase(table, bean);
if (_log.isDebugEnabled())
{
_log.debug("Inserted bean " + origIdentity);
}
if (_ensureFkOrder && _fkTables.contains(table))
{
Identity newIdentity = buildIdentityFromPKs(table, bean);
ArrayList finishedObjs = new ArrayList();
_identityMap.put(origIdentity, newIdentity);
// we're doing multiple passes so that we can insert as much objects in
// one go as possible
ArrayList identitiesToCheck = new ArrayList();
identitiesToCheck.add(origIdentity);
while (!identitiesToCheck.isEmpty() && !_waitingObjects.isEmpty())
{
Identity curIdentity = (Identity)identitiesToCheck.get(0);
Identity curNewIdentity = (Identity)_identityMap.get(curIdentity);
identitiesToCheck.remove(0);
finishedObjs.clear();
for (Iterator waitingObjIt = _waitingObjects.iterator(); waitingObjIt.hasNext();)
{
WaitingObject waitingObj = (WaitingObject)waitingObjIt.next();
Identity fkIdentity = waitingObj.removePendingFK(curIdentity);
if (fkIdentity != null)
{
updateFKColumns(waitingObj.getObject(), fkIdentity.getForeignKeyName(), curNewIdentity);
}
if (!waitingObj.hasPendingFKs())
{
waitingObjIt.remove();
// we defer handling of the finished objects to avoid concurrent modification exceptions
finishedObjs.add(waitingObj.getObject());
}
}
for (Iterator finishedObjIt = finishedObjs.iterator(); finishedObjIt.hasNext();)
{
DynaBean finishedObj = (DynaBean)finishedObjIt.next();
Table tableForObj = _model.getDynaClassFor(finishedObj).getTable();
Identity objIdentity = buildIdentityFromPKs(tableForObj, finishedObj);
insertBeanIntoDatabase(tableForObj, finishedObj);
Identity newObjIdentity = buildIdentityFromPKs(tableForObj, finishedObj);