@Embedded对象如果没有基本数据类型字段,则不会自动实例化

all*_*rog 12 java jpa embeddable ebean

基本问题:为什么@Embedded对象不会被实例化?

有趣的观察是,如果那些不包含基本数据类型(int,boolean ...)或之前未被触及的话,Ebean不会实例化@Embedded对象.例:

@Entity
public class Embedder {
    // getNotAutoInstantiated() will return null if this field was not touched before
    @Embedded
    private NotAutoInstantiated notAutoInstantiated = new NotAutoInstantiated();
    // getAutoInstantiated() will always return an instance!
    @Embedded
    private AutoInstantiated autoInstantiated = new AutoInstantiated();
}

@Embeddable
public class AutoInstantiated {
    // theKey is why this embedded object is always instantiated
    private int theKey; 
    private String field1;      
}

@Embeddable
public class NotAutoInstantiated {
    private String field2;      
}
Run Code Online (Sandbox Code Playgroud)

Syl*_*coy 8

您可能想要检查:

https://hibernate.atlassian.net/browse/HHH-7610

特别是从5.1开始:

static final String CREATE_EMPTY_COMPOSITES_ENABLED

Enable instantiation of composite/embedded objects when all of its
attribute values are null. The default (and historical) behavior is that a null reference
will be used to represent the composite when all of its attributes are null
@since 5.1
@see Constant Field Values
Run Code Online (Sandbox Code Playgroud)

将该hibernate.create_empty_composites.enabled属性设置为true并vo!


Mat*_*ttR 5

我不认为JPA规范清楚地描述了当@Embedded对象的属性全部为null时应该发生的情况,但是至少某些实现将具有null属性的对象视为null对象,这就是您所看到的。

这似乎是一个合理的实现。当然,这在我的代码中(使用Hibernate)很有用,如果我将@Embedded对象设置为null,则希望在我加载持久化版本时将其保持为null。

在您的示例中,AutoInstantiated该类永远不能被认为是空的,因为原始属性theKey永远不能为空。