Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When all columns of an @Embedded field are NULL (JPA / Hibernate) - how to prevent null pointer?

Is there any way to init a empty object, even if all values are null?

@Embeddable
public class Address {
    private String street;
    private String postalCode;
    private String city;
}

@Entity
public class Person {
  @Embedded
  private final Address home = new Address();
}

The problem is, when you hydrate a Person, if all fields of the embedded Address are null, it seems like hibernate is initializing home to null.

It is not initializing it as a "new Address()".

Is there any way to force hibernate to initialize home as "new Address()" even with all fields null?

Trying to avoid things like:

public Address getHome(){
if(home == null){
    this.home = new Address();
}
return this.home;

}

like image 556
S. Shao Avatar asked Sep 15 '25 04:09

S. Shao


1 Answers

You can control this with the hibernate.create_empty_composites.enabled configuration which you can read about in the documentation: https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#_misc_options

like image 95
Christian Beikov Avatar answered Sep 17 '25 18:09

Christian Beikov