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;
}
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:
- true
- false
- 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.
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.
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
精彩评论