Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity members should they be primitive data types or java data types?

Tags:

jpa

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; } 
like image 573
Sam Avatar asked Feb 25 '10 04:02

Sam


People also ask

Should I use primitive types in Java?

As we've seen, the primitive types are much faster and require much less memory. Therefore, we might want to prefer using them. On the other hand, current Java language specification doesn't allow usage of primitive types in the parametrized types (generics), in the Java collections or the Reflection API.

What are the primitive data types of Java?

Primitive data types - includes byte , short , int , long , float , double , boolean and char.

Which is better primitive or wrapper class in Java?

Generally, choose primitive types over wrapper classes unless using a wrapper class is necessary. Primitive Types will never be slower than Wrapper Objects, however Wrapper Objects have the advantage of being able to be null.


1 Answers

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.

like image 154
whiskeysierra Avatar answered Nov 16 '22 16:11

whiskeysierra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!