TinusSky
TinusSky

Reputation: 1737

Add validation rules to Pojo.name to object extending Pojo?

I have a simple java pojo which i give to my android users:

@XmlRootElement
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class PostAccount {
    @Getter
    @Setter
    private String email;
    @Getter
    @Setter
    private String pass1;
    @Getter
    @Setter
    private String pass2;
}

This pojo is serialized to json and send to my server. On my server i which to use jersey bean validation:

public NumberResult add(@Valid ValidAccount account) {

But because the Account pojo doesn't have any validation annotations validation doesn't do much.

I can create a second pojo with validation annotations and use that on server side:

public class ValidAccount {

    @Getter
    @Setter
    @NotEmpty
    @CheckEmail
    private String email;
    @Getter
    @Setter
    @NotBlank
    private String pass1;
    @Getter
    @Setter
    @NotBlank
    private String pass2;
}

Works perfectly.

But when i now add a field at Account pojo i do have to remember to change ValidAccount pojo. No problem, but when you have a lot of pojo's things get complicated to manage.

Is there a better solution?

For example is it possible to extends the Account pojo and in a way add the validation rules? (please i which to continue using annotations, xml gives me the creeps)

Upvotes: 1

Views: 1072

Answers (1)

mipo256
mipo256

Reputation: 3234

For future readers:

In general, you either provide some meta-information at compile time about how exactly you want your entities to be validated and then you use some jakarta-validation-api validation engine (Jeresy, Hiberate whatever), and the engine can validate incoming entity based on annotations you provided. Creating 2 copies of the same entity is not only tedious - it is error prone, so do not do that unless you have a solid justification (in this case it is not the case ,read further).

If there is no annotations, you need to either write validation yourself, or pursue a programmatic configuration aproach. It is similar in some sence to logging java configuration, for instance for logback. You can either provide it in XML file, or programmaticaly. There is no other way, from a logical and theoretical perspective, you need to somehow provide this information to the framework.

So, configuring jakarta-validation-api programmaticaly is vendor dependent. That is, each implementation may have (or may not!) some API that allows you to say "I want this field be not null, not empty and have a length of at least 3 characters". I am aware that Hibernate does have a programmatic validation API. I do not know anything similar in Jeresy validation engine to be honest.

So my suggestion you to either use Hibernate programmatic configuration, or find other implementation that allwos configuring constraints programmatically.

Upvotes: 0

Related Questions