ohseekay
ohseekay

Reputation: 805

Hibernate: any difference between java.lang.Integer and int?

Is there any noticeable difference between

<property name="pwdRetryCount" type="java.lang.Integer">
    <column name="pwd_retry_count" />
</property>

and

<property name="pwdRetryCount" type="int">
    <column name="pwd_retry_count" />
</property>

Upvotes: 10

Views: 9157

Answers (2)

Adam Ostrožl&#237;k
Adam Ostrožl&#237;k

Reputation: 1416

The answer above is totally correct and I just type extra info.

Use nullable types (boxed primitive types like Integer, Double, etc.) for optional values. It depends on your model if it makes sense for particular value to be optional. If it has to have default values, you can create @PreX callbacks (for example @PreLoad) or override getter for returning primitive type with default value instead.

Use primitive types for required value. It has some great benefits if you distinguish among these two approaches like:

  1. If you let hibernate generate DDL, it will automatically create not null constraints for primitive types.
  2. If you do mapping among web dto objects and entities, you have implicit NPE which indicates problem in your code and that behaviour will not make your data inconsistent.

There is one interesting thing though. If you use Lombok library and like to use @Getter and @Setter on entities and you control SelectBeforeInsert behaviour with Persistable interface then you should always use big boxed type like Integer, because you cannot do genericity with primitive type like Persistable<int>. If you use Persistable<Integer> + lombok's @Getter + your ID is named like "id" then you have implicit override getter method for getId. It is just symbiose among lombok + jpa entity.

Upvotes: 2

Ken Chan
Ken Chan

Reputation: 90457

They only have noticeable difference when handling null value.

It is because int is the primitive data type that cannot assign null to it while java.lang.Integer is the wrapper class of int which can accept null .

So , if pwd_retry_count column is nullable and you use int to map your entity object , for the record which pwd_retry_count is null , error occurs as int cannot store null.

Upvotes: 18

Related Questions