001: package net.sourceforge.jaxor.impl;
002:
003: import net.sourceforge.jaxor.CommitBatch;
004: import net.sourceforge.jaxor.EntityChange;
005: import net.sourceforge.jaxor.api.EntityInterface;
006: import net.sourceforge.jaxor.api.UnitOfWork;
007: import net.sourceforge.jaxor.util.SystemException;
008:
009: import java.sql.Connection;
010: import java.sql.SQLException;
011: import java.util.ArrayList;
012: import java.util.List;
013: import java.util.Iterator;
014:
015: /**
016: * A UnitOfWorkImpl maintains lists of new, and dirty entities for a single transaction.
017: */
018: public class UnitOfWorkImpl implements UnitOfWork {
019:
020: private final List _changes = new ArrayList();
021: private boolean _committing = false;
022: private int change;
023: private boolean _batchingEnabled = false;
024:
025: private int getChange() {
026: return change++;
027: }
028:
029: public long size() {
030: return _changes.size();
031: }
032:
033: public void registerUpdate(EntityInterface update) {
034: EntityChange change = EntityChange.update(getChange(), update);
035: if (_committing)
036: update.update();
037: else
038: _changes.add(change);
039: }
040:
041: public void registerNew(EntityInterface newEntity) {
042: EntityChange change = EntityChange.insert(getChange(),
043: newEntity);
044: if (_committing)
045: newEntity.insert();
046: else
047: _changes.add(change);
048: }
049:
050: public int hashCode() {
051: return _changes.size();
052: }
053:
054: public String toString() {
055: return _changes.toString();
056: }
057:
058: public boolean equals(Object obj) {
059: if (obj instanceof UnitOfWorkImpl)
060: return equals((UnitOfWorkImpl) obj);
061: return false;
062: }
063:
064: public boolean equals(UnitOfWorkImpl work) {
065: return _changes.equals(work._changes);
066: }
067:
068: public void batching(boolean isEnabled) {
069: _batchingEnabled = isEnabled;
070: }
071:
072: public void flush(Connection connection) {
073: if (_changes.size() == 0)
074: return;
075: try {
076: _committing = true;
077: for (Iterator iterator = _changes.iterator(); iterator
078: .hasNext();) {
079: EntityChange entityChange = (EntityChange) iterator
080: .next();
081: entityChange.beforeFlush();
082: }
083: CommitBatch batch = new CommitBatch(_changes);
084: try {
085: batch.execute(connection, _batchingEnabled);
086: } catch (SQLException e) {
087: throw new SystemException(e);
088: }
089: for (Iterator iterator = _changes.iterator(); iterator
090: .hasNext();) {
091: EntityChange entityChange = (EntityChange) iterator
092: .next();
093: entityChange.afterFlush();
094: }
095: _changes.clear();
096: } finally {
097: _committing = false;
098: }
099: }
100:
101: public void registerDelete(EntityInterface ent) {
102: _changes.add(EntityChange.delete(getChange(), ent));
103: }
104: }
|