Boxed vs primitive type as entity id

There is no difference between primitive (e.g., int) and its wrapper(e.g., Integer) for entity id. Both are valid according to JPA specification. JPA provider is smart enough to track the state and life cycle of an entity. When entity id is 0 (primitive type) or NULL(wrapper type), JPA provider will generate an id for the entity if id generator is configured. Zero is not regarded as a valid entity id if id is auto generated.

Tested both cases with Cmobilecom JPA, and it works equally well. Off course, no performance difference can be noticed.

Disclaimer: I am a developer of Cmobilecom JPA, a light weight JPA implementation for both Java and Android.


Seems Current Documentation recommends to use Boxed Type.

We recommend that you declare consistently-named identifier attributes on persistent classes and that you use a nullable (i.e., non-primitive) type.


Well, we use non-primitives and we have a strong reason for it. Lots of our fields that are either int/Integer for example have an absolute business value of zero to be perfectly valid. Think of a debt field for example - it is more than OK if the field is zero, meaning you have no debt.

Problem is that with primitives, zero is a default value - so you might accidentally forget to set it for example via a setDebt, thus it might reach your database with a value that you never intended to go there. For this reason we use Integer with some validations that is should never be null for example; but even if we forget to add proper validations, that code will potentially break with a NullPointerException (preferably in tests) and I like an Exception more than inconsistent values in the database.