开发者

How to merge complex business validation with JSR-303?

I'm stuck with validation in my current use case. My app has standard structure (WEB <-> EJB3 Services <-> EJB3 DAO <-> DB). I have an entity which has validation annotations applied to it.

@Entity
class PhoneNumber {

    ...

    private NumberType numberType;
}

w开发者_StackOverflow社区here

enum NumberType {
    FIXED,
    MOBILE,
    ANY
}

Now I have new validation rule to be applied. On PhoneNumber update there should be not possible to change NumberType to ANY if it was set previously to either FIXED or MOBILE.

My Bean Validation rules are checked just before db operations, and the rule above should be applied in service layer (at least I think so) to have a DB access to get previous entity version to compare. But without having bean not yet validated I'm forced to check manually if e.g. numberType is not null.

Can you please provide me some advices or general rules how to deal with more complex busines validations (not only checking single field's values in isolation) when using Bean Validation?


I don't think Bean Validation is the right solution for implementing this kind of business logic.

Instead you could implement this check in the setNumberType() method of the PhoneNumber entity. There you have the old value at hand and compared to an implementation in the service layer there is no chance to perform an illegal state transition by circumventing (accidentally or intentionally) the service implementing the check.


Here you can find a good description of how to write a custom validator which can do "cross-field" validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜