Je n'étais pas trop ravi de l'une ou l'autre des suggestions faites précédemment, alors j'ai créé un aspect qui permettrait de gérer cela pour moi.
Ceci n'est pas entièrement testé, et certainement pas testé contre les collections d'objets incorporés, donc attention à l'acheteur. Cependant, semble fonctionner pour moi jusqu'à présent.
Fondamentalement, intercepte le getter au champ @Embedded
et s'assure que le champ est rempli.
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;
}
}
Voulez-vous dire un élément composite? – Zoidberg
Oui. Pourquoi je ne peux pas répondre avec moins de 15 caractères? –
Je ne suis pas sûr de savoir comment le faire avec des annotations, mais je peux vous montrer le xml – Zoidberg