This is probably going to be frowned upon by purists, but until there is a way to configure hibernate to ensure @Embedded fields are non-null, I've written an AspectJ to populate the value if null.
This isn't fully tested, and definitely not tested against Collections of embedded objects, so buyer-beware.
{code} public aspect NonNullEmbedded {
// define a pointcut for any getter method of a field with @Embedded of type Validity with any name in com.ia.domain package pointcut embeddedGetter() : get( @javax.persistence.Embedded * com.company.model..* );
/** * Advice to run before any Embedded getter. * Checks if the field is null. If it is, then it automatically instantiates the Embedded object. */ Object around() : embeddedGetter(){ Object value = proceed(); // check if null. If so, then instantiate the object and assign it to the model. // Otherwise just return the value retrieved. if( value == null ){ String fieldName = thisJoinPoint.getSignature().getName(); Object obj = thisJoinPoint.getThis(); // check to see if the obj has the field already defined or is null try{ Field field = obj.getClass().getDeclaredField(fieldName); Class clazz = field.getType(); value = clazz.newInstance(); field.setAccessible(true); field.set(obj, value ); } catch( NoSuchFieldException | IllegalAccessException | InstantiationException e){ e.printStackTrace(); } } return value; } }
{code}
|