Hibernate/JPA: Embeddable is initialized altough all properties are null or empty

Viewed 677

I'm using Hibernate and have the following JPA model:

@Entity
public class MyEntity {

  @Embedded
  MyEmbeddable embedded;

}

@Embeddable
public class MyEmbeddable {

    @Column    
    private String name;

    @ElementCollection
    @Enumerated(EnumType.STRING)
    @Size(min = 1)
    private Set<MyEnum> usage;

    @NotNull
    private LocalDate localDate;

}

MyEntity can contain MyEmbeddable, but the whole embeddable should be optional. So I would prefer that MyEntity.embedded is null when all properties of MyEmbeddable are empty or null.

However, when I'm reading such an entity from DB, Hibernate initializes embedded as non-null - which leads to constraint errors when the entity gets flushed to the database again.

As a workaround I would have to write some code to null the embedded property before flushing/persisting - which seems like a very bad idea to me.

I suspect that the ElementCollection causes this inizialitation behaviour - because according to JPA spec ElementCollections are always initialized empty (not null).

Any ideas/hint how you can tell Hibernate to not initialized embedded at all?

1 Answers

Are you sure all embedded column values are null? localDate is annotated with NotNull, so I think that's the issue preventing the embedded property from being null. Also, the @Size(min = 1) on the set looks like it can also be a problem too.

Note that Hibernate provides an option for controlling that behavior (https://in.relation.to/2016/02/10/hibernate-orm-510-final-release/):

Historically Hibernate would always treat all null column values for an @Embeddable to mean that the @Embeddable should itself be null. 5.1 allows applications to dictate that Hibernate should instead use an empty @Embeddable instance. This is achieved via an opt-in setting: hibernate.create_empty_composites.enabled.

See HHH-7610 for details.

Related