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

hibernate, java, jpa, orm, primitive

Solution

- Exception

2.

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

it solves your problem.

Problem

Given this class mapped with JPA (using JPA 1.0 and Hibernate): ``` @Entity public class Foo { private int bar; /* ... */ } ``` - What happens if I try to load a record which has the `BAR` column set to NULL? - 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`.

Original source