Search code examples
javahibernatejpaormprimitive

Primitive type in JPA mapping. What if the database column may be NULL?


Given this class mapped with JPA (using JPA 1.0 and Hibernate):

@Entity
public class Foo {

    private int bar;

    /* ... */
}
  1. What happens if I try to load a record which has the BAR column set to NULL?
  2. Can I specify how to set the bar field when the corresponding column is NULL?

Notes

I know this is not a best practice. The question is more out of curiosity and it is inspired by this situation:

  • The database table is a staging table: adding a NOT NULL constraint is impractical. Bad data is expected, and the point of my code is to validate, clean up and/or reject data before loading it into the "real" database.
  • I have acceptable default values for some fields. For example, a boolean flag which should default to false.

Solution

    1. Exception

    2.

    @Column(name = “bar”, nullable = false, columnDefinition = “bigint(20) default 0″)
    private int bar;
    

    it solves your problem.