Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override @annotations (javax.validation) in a subClass

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

like image 767
MDP Avatar asked Dec 18 '15 15:12

MDP


1 Answers

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.

like image 105
Konstantin Yovkov Avatar answered Sep 25 '22 14:09

Konstantin Yovkov