How can I add a minimum value constraint using Hibernate schema tool?

33 views Asked by At

I am currently adding data validation at all levels of my Spring MVC application.

As I understand it, there is two levels of validation that can be applied to an @Entity annotated JPA entity with corresponding database schema generated by the Hibernate schema generation tool.

  1. Using JPA annotations. This is what informs the Hibernate schema generation tool on how the schema should be generated.

For example:

@Entity
public class Book {
    @Column(length = 50, nullable = false)
    private String title;
}

Would result in the following database schema being generated (MySQL):

CREATE TABLE book ( title VARCHAR(50) NOT NULL );
  1. Using JSR 380 annotations, to actually validate the data at the entity level, before being passed to the database.

The example above, but this time using JSR 380 annotations to validate at the entity:

@Entity
public class Book {
    @Size(max = 50)
    @NotNull
    private String title;
}

I've been searching online for how I could do something like this

CREATE TABLE book (quantity CHECK (quantity > 0));

using JPA, but I've only come across the @Min annotation from JSR 380.

@Entity
public class {
    @Min(0)
    private int quantity;
}

If my understanding of the separation of these two layers is correct, this is validating the data to be non-negative at the entity level, but not at the actual persistence level. Is it possible to define such CHECK statements at the JPA level of an entity?

0

There are 0 answers