We are extending User entity which is standard entity which we can not modify at all.
Email field is in user entity so how do we apply mandatory validation?
Unfortunately, there is no easy way to extend existing entities with Bean Validation, but you can create a simple meta property and add your validators there in the extended entity.
Use the following trick:
@Extends(User.class)
@Entity(name = "demo$ExtUser")
public class ExtUser extends User {
private static final long serialVersionUID = 1150002660073436509L;
public void setCustomerEmail(String customerEmail) {
this.email = customerEmail;
}
@Email(message = "Should be valid email")
@Length(message = "Email should have min 3 and max 50 length", min = 3, max = 50)
@NotNull
@Transient
@MetaProperty(mandatory = true, related = "email")
public String getCustomerEmail() {
return this.email;
}
}
As you see, we simply provide additional getter / setter instead of separate column in the database.