allprog allprog - 5 months ago 54
Java Question

@Embedded object not instantiated automatically if it has no basic datatype fields

Fundamental question: Why aren't @Embedded objects always instantiated?

The interesting observation is that Ebean does not instantiate @Embedded objects if those do not contain basic datatypes (int, boolean...) or weren't touched before. Example:

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

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

public class NotAutoInstantiated {
private String field2;


I don't think the JPA spec clearly describes what should happen when an @Embedded object's properties are all null, but at least some implementations treat an object with null properties as a null object, which is what you're seeing.

This seems like a reasonable implementation. Certainly it's been useful in my code (using Hibernate) where if I set an @Embedded object to null I want it to remain null when I load a persisted version.

In your example, the AutoInstantiated class can never be considered null, since the primitive property theKey can never be null.