我可以让一个嵌入休眠实体非空?
-
19-09-2019 - |
题
什么我想要的:
@Embedded(nullable = false)
private Direito direito;
然而,如你所知还有没有这种属性@嵌入。
是否有一个正确的方式做到这一点?我不想解决方法。
解决方案
嵌入部件(或复合元件,不管你想要打电话给他们)通常包含多个属性,从而被映射到一个以上的列。整个部件被空因此可以以不同的方式进行处理; J2EE规范没有规定一种方式或另一种。
休眠认为组件是NULL,如果其所有属性都为NULL(反之亦然)。因此,您可以声明的属性之一(有)不为空(或者在@Embeddable
或@AttributeOverride
上@Embedded
的一部分)来实现你想要的东西。
另外,如果你在使用Hibernate验证器,你可以用注释您@NotNull
物业虽然这只会造成应用级的检查,没有DB-水平。
其他提示
它是可能的使用"休眠状态。create_empty_composites.启用的"由于休眠5.1来改变这种行为(见 https://hibernate.atlassian.net/browse/HHH-7610 )
虚拟字段添加到被标记@Embeddable类。
@Formula("0")
private int dummy;
我不符合任何先前提出的建议过于激动,所以我创建了一个会处理这对我来说一个方面。
此不完全测试,绝对不是对嵌入对象的类别测试,所以买方提防。然而,似乎为我工作至今。
基本上,截取该吸气剂的@Embedded
场并确保字段被填充。
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;
}
}
可以使用nullsafe吸气剂。
public Direito getDireito() {
if (direito == null) {
direito = new Direito();
}
return direito;
}
不隶属于 StackOverflow