Search code examples
jpa-2.0bean-validationhibernate-validator

Configure Hibernate 4.1, JPA2 with Spring 3.1.1. to update DB schema from JSR 303 Annotations


In my current Hibernate 4.1 + JPA 2 + Spring 3.1.1 configuration the generated create table statement doesn't take JSR 303 @javax.validation.constraints.NotNull annotation into consideration.

Class declaration:

@Entity
public class MenuItem implements Serializable {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String title;

    @NotNull    // <--- JSR 303 constraint annotation
    private String description;

    ...
}

Generated create table statement:

create table menu_item (
    id bigint generated by default as identity,
    description varchar(255),   // <--- should be not null
    price binary(255),
    title varchar(255),
    primary key (id)
)

However, if I add JPA @javax.persistence.Column annotation, the create table statement is generated correctly.

Class declaration:

@Entity
public class MenuItem implements Serializable {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String title;

    @NotNull                 // <--- JSR 303 constraint annotation
    @Column(nullable=false)  // <--- JPA annotation
    private String description;

    ...
}

Generated create table statement:

create table menu_item (
    id bigint generated by default as identity,
    description varchar(255) not null,   // <--- generated not null
    price binary(255),
    title varchar(255),
    primary key (id)
)

Is it possible to configure Hibernate 4.1 + JPA 2 + Spring 3.1.1 to generate DB schema only from JSR 303 annotations?


Solution

  • No, it is not possible. Only in the case if we widen definition of configure to implement it is possible. JPA 2 itself gives about two pages in specification to Bean validation. Also about DB schema generation from mappings it is not too strict:

    It is permitted, but not required, that DDL generation be supported by an implementation of this specification.

    Also I am not aware about Hibernate or Spring providing such a functionality. It is of course bit repetitive to use both @NotNull & nullable=false.