Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@NotNull on subclass getter affects parent class table

I have a question related to javax.validation.constraints.NotNull annotation. In my project i do have classes tree like following :

@Inheritance(strategy = InheritanceType.JOINED)
class Ssss {
    @ManyToOne
    private Xxxx x;
    public Xxxx getXxxx() {
       return x;
    }
}

@Inheritance(strategy = InheritanceType.JOINED)
class Yyyy extends Ssss {
    @Override
    //some not important annotations
    public Xxxx getXxxx() {
        return super.getXxxx();
    }        
}

@Inheritance(strategy = InheritanceType.JOINED)
class Zzzz extends Ssss {
    @Override
    //some not important annotations
    @NotNull
    public Xxxx getXxxx() {
        return super.getXxxx();
    }
}

This three classes are stored in database as three tables. For schema creation i'm using Hibernate:

hibernate.hbm2ddl.auto=create

Is it an expected behavior that Hibernate adds NOT NULL on xxxx_object_id field stored in table generated for super class ssss like following:??

Postgres

I could not find any relevant information about how hibernate treats @NotNull on inherited getters.

Can anyone help me on this issue?
Best Regards.
Michal

like image 562
Michal W Avatar asked Feb 07 '17 08:02

Michal W


1 Answers

Yes. Hibernate has constraints which it keeps checking in case of conflicts.
Here is an example:

@Inheritance(strategy = InheritanceType.JOINED)
class Ssss {

   @ManyToOne
   private Xxxx x;
   public Xxxx getXxxx() {
      return x;
   }
}

If it was this much, then hibernate has no Conflict as it makes x of type Xxxx as null
But here is the issue, in this code:

@Inheritance(strategy = InheritanceType.JOINED)
class Zzzz extends Ssss {
   @Override
   //some not important annotations
   @NotNull
   public Xxxx getXxxx() {
       return super.getXxxx();
   }
}

Here Hibernate via @NotNull annotation is told to make the x type of Xxxx as @NotNull
In the above two cases, there is a conflict, for Ssss it can be Null and Zzzz it cannot be null. To infer that and resolve the conflict, Hibernate makes Xxxx type variable of Ssss as NotNull as well.

like image 181
Tahir Hussain Mir Avatar answered Sep 23 '22 16:09

Tahir Hussain Mir