Hi, I want to add some modification informations to an object. The history of that object is stored in a list of ModificationHistoryElement's. To this list I want to add an new Entry.
Code:
public class HistoryLogInterceptor extends EmptyInterceptor {
private static Logger LOG = Logger.getLogger(HistoryLogInterceptor.class);
@Override
public boolean onFlushDirty(final Object entity, final Serializable id, final Object[] currentState,
final Object[] previousState, final String[] propertyNames, final Type[] types) {
LOG.debug("onFlushDirty");
return updateHistory(entity, currentState, propertyNames);
}
@Override
public boolean onSave(final Object entity, final Serializable id, final Object[] state,
final String[] propertyNames, final Type[] types) {
LOG.debug("onSave");
return updateHistory(entity, state, propertyNames);
}
private boolean updateHistory(final Object entity, final Object[] state, final String[] propertyNames) {
if (entity instanceof SteuerObjekt) {
final VitaxDatabaseUser currentUser = Simulationsmodell.getCURRENT_USER();
/* find properties and set last change user and timestamp */
for (int i = 0; i < propertyNames.length; i++) {
final String propertyName = propertyNames[i];
if (propertyName.equals("history")) {
final List<ModificationHistoryElement> history = new PersistentList();
history.addAll((Collection<ModificationHistoryElement>) state[i]);
final ModificationHistoryElement newEntry = new ModificationHistoryElement(
Simulationsmodell.getCURRENT_USER(), VQualityOfEnteredData.MODIFIED);
history.add(newEntry);
state[i] = history;
LOG.debug("History element added.");
/* Hibernate expects true, if we changed anything */
return true;
}
}
}
return false;
}
}
This cause an "org.hibernate.LazyInitializationException".
Casting state[i] to an List and to add the newEntry doesn't also works. It causes an
"org.hibernate.TransientObjectException".
I tried to save it before with getCurrentSession and
Code:
HIBERNATE_PROPERTIES.setProperty(org.hibernate.cfg.Environment.CURRENT_SESSION_CONTEXT_CLASS,
org.hibernate.context.ThreadLocalSessionContext.class.getName());
but no transaction is open at this point.
Sure I could open a new transaction or use openSession with a new transaction, but this would violate the transaction requirements of the transaction which triggered the interceptor. Cause if this transaction would be rolled back the new history-entry won't be deleted. So this can't be a solution.
The history-element contains three attributes:
Code:
private String vitaxUser = "Unknown";
@Enumerated(value = EnumType.STRING)
private QualityOfEnteredData quality;
@Temporal(value = TemporalType.TIMESTAMP)
private Calendar timestamp;
Thanks a lot.
Greetings Michael