Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a long type is actually NULL?

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) {
    //...
}
like image 995
UpHelix Avatar asked Jan 05 '12 20:01

UpHelix


People also ask

Can long data type be null?

Whereas a Long object reference can be null, a primitive long can not.

How do you check if a string is null?

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.

How do you know if something is null?

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 .

How do you check if a long variable is null in C#?

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 .


2 Answers

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.

like image 146
Marcelo Avatar answered Oct 10 '22 21:10

Marcelo


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);
  // ...
}
like image 23
maerics Avatar answered Oct 10 '22 20:10

maerics