views:

212

answers:

2

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  A: 

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.

Robert Petermeier
I'd like better to use something not tied with Hibernate...
pajton
Hm, maybe this is a solution. I was looking rather for some kind of trick, a fast way. Also, I am talking about DB level constraint, not client validation.
pajton
+2  A: 

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).

Pascal Thivent