Spring JPA with Hibernate handle null sub entities when foreign key join is present

Viewed 1129

So let's say I have two tables called student and class. class id is a foreign key in student table. The class id column for some students might also be empty (means no class is assigned to them). If we use spring jpa to fetch data for such students, then the class entity object would be null. I would rather want an empty object instead of null so that manual null checks are avoided. How do I achieve this?

Student Entity - Student Id, Name, Age, Class Id
Class Entity - Class Id, Class Name, Appointed Teacher Name

3 Answers

Anyhow you endup with a direct or in-direct manual check.

Fetching records as java 8 optional would help.

When you use field-type access, you can implement the getter and setter methods in your own way. You can, for example, implement a getMyValue() method which wraps the myValue attribute in an Optional

@Entity
public class SomeClass {

...

@Column
private String myValue;

 ...

 public Optional getMyValue() {
    return Optional.ofNullable(myValue);
 }

 public void setMyValue(LocalDate myValue) {
    this.myValue= myValue;
 }
...
}

Hibernate 5.2 also introduced the loadOptional(Serializable id) method to the IdentifierLoadAccess interface which returns an Optional. You should use this method to indicate that the result might be empty when you can’t be sure that the database contains a record with the provided id

The change is rather trivial and plain old Java. I also do this for Collections in my JPA applications.

Simply do a null check in the getter of the entity.

    public Class getClass() {
        if (null == this.myClass) {
            return new Class(); // assuming the default constructor resembles an empty class
        }
        return this.myClass;
    }

If there is no real "empty" Class in your code, simply return an Optional<Class> instead.

EDIT: By the way, using "Class" is a pretty dangerous idea for a name, as it clashes with Java's class keyword.

You could use a @PostLoad method to set the class to some dummy value after a student gets loaded. But you must not persist that entity because JPA would try to persist that dummy instance.

I therefore would go the full distance and create a row in the database for NO_CLASS and instead of having a null id reference that row. This way your object model matches the data model.

Related