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

2022-09-03 12:53:37

基本问题:为什么@Embedded对象并不总是实例化?

有趣的观察结果是,Ebean不会实例化@Embedded对象,如果这些对象不包含基本数据类型(int,布尔值...)或者以前没有接触过。例:

@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;      
}

答案 1

对于休眠,您可能需要查看问题 HHH-7610

特别是,自 5.1 以来,有一个实验性功能可以更改此行为。请注意,此功能存在已知问题,在稳定之前不应在生产中使用。这在 org.hibernate 的 Javadocs 中进行了详细说明.cfg.AvailableSettings):

/**
 * [EXPERIMENTAL] Enable instantiation of composite/embedded objects when all of its attribute values are {@code null}.
 * The default (and historical) behavior is that a {@code null} reference will be used to represent the
 * composite when all of its attributes are {@code null}
 * <p/>
 * This is an experimental feature that has known issues. It should not be used in production
 * until it is stabilized. See Hibernate Jira issue HHH-11936 for details.
 *
 * @since 5.1
 */
String CREATE_EMPTY_COMPOSITES_ENABLED = "hibernate.create_empty_composites.enabled";

将属性设置为 true 和 voilà!hibernate.create_empty_composites.enabled


答案 2

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

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

在您的示例中,该类永远不能被视为 null,因为基元属性永远不能为 null。AutoInstantiatedtheKey


推荐