1

This question is similar to Pete_Gore's but for spring hibernate. I want to create an Entity with an Embedded object which the Embedded object can be nullable, but if it is defined then the properties in the Embedded object should be non-nullable.

Entity.java

@Entity
public class EntityObject {

    @Column
    private String name;

    @Embedded
    private EmbeddedObject embeddedObject;// This should be nullable

    //Getters, setters, and constructor
}

Embedded.java

@Embeddable
public class EmbeddedObject {
    @Column(nullable = false)
    private String exampleProperty;// This should be non-nullable

    //Getters, setters, and constructor
}

This scenario works when exampleProperty is nullable but when I set it to be non-nullable I get an error similar to the following when creating an EntityObject with a null EmbeddedObject.

NULL not allowed for column "exampleProperty"; SQL statement:
Kyle Pfromer
  • 1,485
  • 1
  • 15
  • 26

2 Answers2

0

Add in your embeddable class:

@Formula("0")
int aNUll;
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • I believe this results in the exact opposite of what the OP is looking for. This results in a non-null embedded object, even if all of its fields are null. The question is asking about having a nullable embedded object, that contains non-null fields – pedorro Sep 07 '21 at 19:35
0

The way I achieved this is by separating the Embeddable class into its own table. This is done by declaring a @SecondaryTable on the main Entity class. And then each field of the Embedded class must specify that it uses that table. So your example would be something like this:

Entity:

@Entity
@SecondaryTable(name = "embedded_table", pkJoinColumns = @PrimaryKeyJoinColumn(name = "entity_name"))
public class EntityObject {

    @Column
    private String name;

    @Embedded
    private EmbeddedObject embeddedObject; // this is nullable

    //Getters, setters, and constructor
}

Embedded:

@Embeddable
public class EmbeddedObject {
    @Column(nullable = false, table = "embedded_table")
    private String exampleProperty; // this is not nullable

    //Getters, setters, and constructor
}

In general, the idea is that Embedded/Embeddable are trying to merge multiple classes into a single database table. Whereas SecondaryTable instructs JPA to split what would otherwise be a single table, into two. As a single table, any entity row would require values for all non-null fields, even ones for the embedded type. As separate tables, the relational semantics permit that no embedded table row exist for an entity row where the embedded object is null. But, if the embeded object is present, a corresponding row will be added to the embedded table, at which point all non-null values must be defined.

I got some inspiration for this from here: https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables

pedorro
  • 3,079
  • 1
  • 24
  • 24