Hibernate Interceptor Issue
Hello forum members,
Please forgive me for any errors as this is my first posting.
I cannot seem to get the previous state of entities associated with a dirty entity. When I drill down to the set of associated objects through the currentState and previousState arrays and compare property values, the values are always the same even though I have changed them directly.
The code below illustrates the problem. The first code snippet displays the application code that sets my entity properties. The second is where I compare previous and current values. I have two entities that I'm interested in (EntityA and EntityB). EntityA contains a set of EntityB. My application makes changes to EntityA's stringProperty field and to one of associated entityB's fields (called here "property1").
snippet 1
...
Query q = session.createQuery("from EntityA where EntityAId=?");
q.setParameter(0, "100");
List list = q.list();
Set setB;
for (Iterator it = list.iterator(); it.hasNext();) {
ea = (EntityA) it.next();
log.info("EntityA=" + ea);
log.info("Initial property amount=" + ea.getProperty());
//Set to random number for test purposes
ea.setPropertyAmount(new Double(Math.round(rand.nextDouble()*100000)));
log.info("New property amount=" + ea.getPropertyAmount());
setB = ea.getEntityBs();
for (Iterator bIt = setB.iterator(); bIt.hasNext();) {
EntityB entityB = (EntityB) bIt.next();
log.info("Initial EntityB property1=" + entityB.getProperty1());
//assume previous value is "bar"
entityB.setProperty1("foo");
log.info("New EntityB property1=" + entityB.getProperty1());
}
}
...
snippet 2
...
public boolean onFlushDirty(Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types) throws CallbackException {
if (entity instanceof EntityA) {
for (int i = 0; i < propertyNames.length; i++) {
if ("stringProperty".equals(propertyNames[i])) {
log.info("EntityA Property " + propertyNames[i] + " new=" + currentState[i] + " old=" + previousState[i]);
}
if ("setProperty".equals(propertyNames[i])) {
log.info("EntityA Property " + propertyNames[i] + " new=" + currentState[i] + " old=" + previousState[i]);
Set setB1 = (Set) previousState[i];
Set setB2 = (Set) currentState[i];
EntityB entityB1 = (EntityB) setB1.iterator().next();
EntityB entityB2 = (EntityB) setB2.iterator().next();
log.info("Previous EntityB property1=" + entityB1.getProperty1());
log.info("Current EntityB property1=" + entityB2.getProperty1());
}
}
}
...
I find that I get the same value for property1 in the EntityB taken from the previousState as the value for property1 in EntityB taken from the currentState. Is there any way to get the previous value of associated entities when trapping a dirty entity in onFlushDirty?
|