35

Is there a difference in declaring the enabled variable as Boolean or boolean? Which is preferable from a memory footprint perspective.

@Entity
class User {

     @Column
     Boolean enabled;
}

3 Answers 3

43

I would usually suggest using the primitive types, just to get rid of null checks all over the place. But it really depends on what you want to say. Your Boolean now can hold 3 values:

  1. true
  2. false
  3. null

And null can make a total new semantic when dealing with entities. I usually use it as "No data available". Your "enabled" might be a bad example for this kind of field. But lets say you have a number which holds the age of a person.

private Integer age;

When you use null, you can treat this as: "Unknown". You could also use an int and define a special value (-1) for this case, but null is the more natural solution.

So, to sum it up. Use primitives if there is always a meaningful value (required fields?) and wrapper classes for optional values.

27

They'll both map to the same column type.

From a memory perspective, a primitive would probably be a little lighter, but the difference is almost certainly going to be negligible.

I think a primitive would make it non-nullable, but you could also do that with an annotation.

3
  • Thanks, I will stick with the java data type to avoid special handling of nulls
    – Sam
    Commented Feb 25, 2010 at 5:27
  • As far as I know there is difference both in memory footprint and execution time. For more information I refer you to this post: baeldung.com/java-primitives-vs-objects
    – Conscript
    Commented Mar 9, 2021 at 10:31
  • 5
    Keep in mind that if you use a primitive type for a field in your Entity and read an already existing row in a table where the matching column for that field is NULL then JPA will throw an IllegalArgumentException when you try to query that table using your Entity. Commented Mar 29, 2021 at 19:50
11

Kaleb's right - if any queries return a null value for "enabled" (in this case) then you have to use the object rather than the primitive.

This is from the Hibernate FAQ:

A PropertyAccessException often occurs when the object being passed to the setter method is of the wrong type. Check your type mappings for the offending property. (To see exactly which property was the problem, you might need to disable the CGLIB reflection optimizer.) However, the most common cause of this problem is that Hibernate attempted to assign null to a property of primitive type.

If your object has a primitive-type property mapped to a nullable database column then you will need to use a Hibernate custom type to assign a sensible default (primitive) value for the case of a null column value. A better solution is usually to use a wrapper type for the Java property.

https://www.hibernate.org/116.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.