问题
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