Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 257
Danilo Piazzalunga Avatar asked Feb 15 '13 11:02

Danilo Piazzalunga


People also ask

Can a primitive data type be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.

What is primitive null type?

Null used as default Just as there is a default value for primitive types (e.g., 0 for integers, false for booleans), null is the default value for reference types.


1 Answers

I would rather use objects if a column may contain null value because Matheus's idea introduces false data. NULL <> 0!

like image 52
Michael-O Avatar answered Nov 15 '22 13:11

Michael-O