Java Reference
In-Depth Information
((Collection) stored.get()).add(mailshot);
}
return false;
}
Finally, we don't necessarily have enough information to prepare our mailshot—the
e-mail address may be missing. If the name field actually represents the e-mail address, then
we are fine; but if it represents a key into other objects, and hence tables in the database, then
we have to be careful. It is possible to write database logic from within an interceptor, but the
risk of accidentally recursing back into your interceptor logic is high, so we don't recommend
it. It's slightly less tricky if you are only using a session-scoped interceptor, but there are prob-
ably safer ways to achieve the same end result.
In this example, the methods that we are not using have been given a default implemen-
tation. You will note that some of these methods return null or false . These methods are
permitted to change the data that is preserved or returned by the session. Returning to the
onSave() method, we will consider another possible implementation, shown in Listing A-28.
Listing A-28. Changing the Data from Within an Interceptor
public boolean onSave(Object entity, Serializable id,
Object[] state, String[] propertyNames, Type[] types)
throws CallbackException
{
if( entity instanceof Booking ) {
state[1] = "unknown";
}
return true;
}
Here we are altering the state array. This contains the values of each of the objects' fields
that are to be stored (in the order defined in the mapping file). In our Booking class, field 0 is the
id , field 1 is the name , and field 2 is the seat —so here we have changed the name value to be pre-
served in the database. Returning true causes Hibernate to reflect this change when it saves the
data. If we left the return flag as false , nothing would happen when the method was called.
The temptation is to assume that returning false guarantees the safety of the data to be
preserved, but, in fact, this is not the case. The state array represents copies of the data to
be preserved—but we have also been given access to the actual object (entity) that contains
the original values. If you amend the fields of the entity before returning, the flag will not pre-
vent your changes from being made. Listing A-29 illustrates how this might occur.
Listing A-29. Changing the Data in an Unorthodox Way
public boolean onSave(Object entity, Serializable id,
Object[] state, String[] propertyNames, Type[] types)
throws CallbackException
Search WWH ::




Custom Search