Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Primitives or wrappers in JPA2.0?

I have seen this question at SO which tends to lead towards Primitives and also seen this one from coderanch which tends to lead towards wrappers. Both are slightly old too.

I do not have any special needs just want to know a standard good practice.

Examples on web are mixed too. e.g some with go like this:

@Id
@Column(name = "CUSTOMER_ID")
public long customerId;

Others with Wrappers:

@Id
@Column(name = "CUSTOMER_ID")
public Long customerId;
like image 909
Java Ka Baby Avatar asked Feb 05 '12 04:02

Java Ka Baby


People also ask

What is the difference between wrapper class and primitive?

The difference between wrapper class and primitive type in Java is that wrapper class is used to convert a primitive type to an object and object back to a primitive type while a primitive type is a predefined data type provided by the Java programming language.

Are primitives faster than objects?

Usage. As we've seen, the primitive types are much faster and require much less memory. Therefore, we might want to prefer using them.

Are wrapper classes primitive?

Wrapper classes can be used to store the same value as of a primitive type variable but the instances/objects of wrapper classes themselves are Non-Primitive. We cannot say that Wrapper classes themselves are Primitive types. They just wrap the primitive types.


2 Answers

The difference between the two is nullability. the primitive type is unable to be null, while the "Wrapped" type can be null.

I prefer to use the wrapped type as you can tell if the object has been saved/loaded to/from the database whether or not the id value is null.

I don't think there is a "best practice" here, maybe a matter of style?

like image 124
John Ericksen Avatar answered Oct 05 '22 21:10

John Ericksen


Hibernate recommends you:

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

like image 41
Jama A. Avatar answered Oct 05 '22 20:10

Jama A.