You could use an Interceptor or an EventListener to generate the value when the entity is saved to the database. It wouldn't be ideal because the interceptor/eventlistener is triggered for every entity that is saved and not just entities of a specific type, but you could implement the logic to only apply to instances of a specific class and only generate the value if the value is null.
Something like the following (uses Interceptors):
Code:
public class GeneratePropertyValueInterceptor extends EmptyInterceptor {
...
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
if ( entity instanceof ClassWithPropertyValueToGenerate) {
for ( int i=0; i<propertyNames.length; i++ ) {
if ( "propertyToGenerateValue".equals( propertyNames[i] ) ) {
if (state[i] == null) {
state[i] = functionThatGeneratesValue();
return true;
}
}
}
}
return false;
}
...
}
Using an EventListener would be similar. I'm not sure if one is preferable to the other. You can get more information about Interceptors and EventListeners from the Hibernate manual (Chapter 14).
This will be more difficult if your function for generating the value requires arugments that are not available at this point.