Express not trivial constraints in JPA

六月ゝ 毕业季﹏ 提交于 2020-01-15 09:55:49

问题


What is the best way to express range constraint in JPA? I would like to express something like 'this column can only take values between 1..5'.

Probably I could use @PrePersist and @PreUpdate for that.

Is there a better way?


回答1:


The Bean validation (JSR 303) is a standard, Hibernate Validator is just an implementation (the RI more precisely) so this doesn't really tie you with Hibernate. And although Bean Validation 1.0 is part of Java EE 6, it can be used "outside" a Java EE 6 container. It allows to do things like this:

public class Address {

    @NotNull private String line1;
    private String line2;
    private String zip;
    private String state;

    @Length(max = 20)
    @NotNull
    private String country;

    @Range(min = -2, max = 50, message = "Floor out of range")
    public int floor;

        ...
}

The recent Bean Validation with JPA 1.0 blog post shows how to use this API with JPA 1.0 with an entity listener (performing validation on @PrePersist and @PreUpdate).




回答2:


There is JSR 303 which is implemented by Hibernate Validator which can be used for this purpose. I'd say it depends on your web framework (if you're building a web app) how well this can be used to perform client-side validation, though. We're currently trying to integrate this with a GWT app.

Google and SO come up with another implementation which I didn't know so far: agimatec-validation.



来源:https://stackoverflow.com/questions/2380498/express-not-trivial-constraints-in-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!