Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce a validation constraint on an Embeddable entity property?

I have a Person entity with an Email collection property:

@ElementCollection
@CollectionTable(schema="u",name="emails",joinColumns=@JoinColumn(name="person_fk"))
@AttributeOverrides({
    @AttributeOverride(name="email",column=@Column(name="email",nullable=false)),
})
public List<EmailU> getEmails() {
    return emails;
}

In my Email class, I tried to annotate email with @Email:

@Embeddable
public class EmailU implements Serializable {
    private String email;

    public EmailU(){
    }

    @Email
    public String getEmail() {
        return email;
    }
}

But it doesn't work. What should be my approach here?

like image 239
ftkg Avatar asked Dec 21 '12 14:12

ftkg


1 Answers

Add a @Valid annotation to your collection property. This triggers your validation provider to validate each item in the collection, which will then call your @Email validator.

@Valid
@ElementCollection
@CollectionTable(schema="u",name="emails",joinColumns=@JoinColumn(name="person_fk"))
@AttributeOverrides({
    @AttributeOverride(name="email",column=@Column(name="email",nullable=false)),
})
public List<EmailU> getEmails() {
    return emails;
}

Annotation Documentation: http://docs.oracle.com/javaee/6/api/javax/validation/Valid.html

like image 53
Perception Avatar answered Oct 09 '22 06:10

Perception