We have a nullable (type long) column (named referral) in our MySQL database. We use hibernate for ORM.
I am trying to get the value of the column for a given member. Some are null, and if its not, its an id that points to another member whose is the referrer.
The problem is in the java code I am trying to detect if that member's column is null, if not, do something.
String referrerAffiliateId = Long.toString(member.getReferral());
if (referrerAffiliateId != null){
//do something
}
member.getReferral() returns the value (type long) of the referral column. Some of those columns are null and some are not.
The above code compiles fine, but I get a nullPointerException when I call the method on a user whose referral column is null.
How do I properly do a detection on this?
Thanks in advance!
Full Answer:
Thanks to @Marcelo for the best correct answer.
Here is the code in its final state:
Long referrerAffiliateId = member.getReferral();
if (referrerAffiliateId != null) {
//...
}
Whereas a Long object reference can be null, a primitive long can not.
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .
Use the HasValue property of the Nullable<T> . Alternatively, you can use GetValueOrDefault to return the contained value if the Nullable has a value or otherwise default(T) . For Nullable<int> and Nullable<long> it will be 0 , for Nullable<string> (or any reference type), it will be null .
Assuming member.getReferral()
returns a Long
, use:
if (member.getReferral() != null)
In Hibernate, if you want to be able to detect nullability in a property, you must not use primitive types, because they will always have a default value 0
for longs.
The exception probably comes from Long.toString()
, try checking the value before converting to a string:
Long ref = member.getReferral();
if (ref == null) {
// Do something...
} else {
String referrerAffiliateId = Long.toString(ref);
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With