Rajesh Balan
Rajesh Balan

Reputation: 643

How can I pass NULL value in SqlData implementation for Long typed attribute?

I have loads of raw data (of type SqlData objects) coming in and trying to insert into Oracle using a user defined type created.

The problem is only for the records which has some Long attributes that are null. I get a NullPointer exception for these records - as it tries to invoke toString on a null object.

Is there any way to write null values for Long column (in SQLOutput stream)?

I know this is possible by changing into String type, but I can not touch on the PL/SQL function as this is used from many places.

public classMyClass extends MyBaseType implements SQLData {

public void writeSQL(SQLOutput stream) throws SQLException {

    stream.writeString(getSource());
    stream.writeTimestamp(getDtm());
    stream.writeString(getUniqueId());
    stream.writeString(getType());

    stream.writeLong(getResponseCode());

The last line causes NullPointer Exception when getResponseCode() is null.

Any idea how to handle this without changing the type (to String)?

The last option tried was,

private void writeNullPossibleNumber(SQLOutput stream, Integer intValue) throws SQLException {

    if (intValue==null) {
        stream.writeBigDecimal(null);
    } else {
        stream.writeInt(intValue);            
    }
}

The above solution is working properly.

Reference: http://docs.oracle.com/cd/A87860_01/doc/java.817/a81357/sampcod3.htm

Thanks for all the help

Upvotes: 4

Views: 2092

Answers (3)

tibtof
tibtof

Reputation: 7957

You get NPE because of autounboxing. You should explicitly write null values, try something like this:

if (getResponseCode() != null) stream.writeBigDecimal(new BigDecimal(getResponseCode()));
else stream.writeBigDecimal(null);

Upvotes: 1

ErstwhileIII
ErstwhileIII

Reputation: 4853

You can either of the following options:

  • Explicitly use NULL for the null value (use an if statement to select NULL or the toString)
  • Eliminate the column from in the insert if the value is null

Something like the following helper class might be useful to you.

public class DatabaseHelper {
private static final String CNULL = "NULL";

static public String fixValue(Object value) {
    if (value == null) {
        return CNULL;
    } else {
        return value.toString();
    }
}
}

Upvotes: 0

Artem Bilan
Artem Bilan

Reputation: 121482

As you see SQLOutput.writeLong waits primitive long, but you seems try to provide the wrapper Long. In this case, of course, null can't be converted to any primitive.

So, or just add null check before writeLong, or change the entire logic, if it isn't OK for you write nulls to DB at all.

Upvotes: 1

Related Questions