Boxed vs primitive type as entity id

Mahozad :

In JPA (Hibernate implementation) Which type is better to use as the entity id: Boxed type (e.g. Integer) or Unboxed type (e.g. int)?

A friend said that you should use Boxed types because when you create a new entity in your program, Hibernate sees that the id is null and understands that it should create a new row in database (In contrast if id is not null Hibernate may update an existing row in databse).

But the id of my entities was int and it worked well without any error and we know that the default value of primitive instance variables is 0. So he said that maybe hibernate treats 0 as special and assumes that the object is a new one.

Eugene :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35313&siteId=1