7

I have this Entity, that is a super class:

@Entity
public class Father implements Serializable{    

    @Column(name = "name")
    @Size(min=1, max=10)
    @Pattern(regexp="^[A-Za-z ]*$")
    @NotNull
    private String name;

}

this one, extends the one above:

@Entity    
public class FatherSub extends Father implements Serializable{  

    private String name;

}

As you can see, in FatherSub I don't have @Annotations and I don't want them. How can I override them? Is there a way?

It seems that the annotations @NotNull persist in the subclass and ask me to fill Father.name (not FatherSub.name) as you can see in these 2 Eclipse printscreen pics.

enter image description here enter image description here

Thank you

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
MDP
  • 4,177
  • 21
  • 63
  • 119

1 Answers1

5

Annotations, which just represent some meta info for some specific period of time, are not over-writable when having a subclass. So it's up to the implementation how annotation inheritance is implemented. For the Validator Framework, annotations scattered over multiple inherited classes are aggregated.

In your example, the FatherSub#name member hides the Father#name member. This means that all instances of FatherSub will work with the name defined in FatherSub. But because the Validation implementation takes also inherited annotations into account, though the FatherSub#name does not have a @Column annotation, the error pops up. You can't change this behaviour, so you must choose to either not use inheritance at all or give the child class the validator annotations instead of the parent.

Additionally, you don't need to explicitly implement Serializable in FatherSub, as Father already implements it.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • I am using `@NotNull` annotation on properties in the child class but hibernate adds not null constraint on created tables anyway. I have tried both SINGLE_TABLE and JOINED strategies. Do you know how to solve this issue? – Conscript Apr 27 '21 at 11:04