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

Time:08-01

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;

}

CodePudding user response:

If this is your only code, then there is nothing here that will produce a NPE. If you are calling something like getHome().getStreet().length() then it will if the field street was set to null based on the results of the query. This is the correct behavior, and you shouldn't attempt to change it. This way it's up to you to write your code in a manner that's null-safe.

If you still just want to have these fields as an empty String rather than Null, then you can create a custom type in Hibernate. Implement org.hibernate.usertype.UserType, in the nullSafeGet and nullSafeSet methods, you'll return an empty String in place of any null values. Then you'd simply annotate your fields with @Type()

@Type(type = "com.acme.MyCustomType")
private String street;

Again, I would highly recommend AGAINST taking this approach as you're going to end up with more headaches than just dealing with NPEs

CodePudding user response:

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

  • Related