Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling setProperty with int but getProperty returns Long on google app engine persistent storage

When using this code with DatastoreService I get ClassCastException Long acnnot be cast to integer in fromEntity. Is it normal behaviour? (I get this behaviour when debugging on local computer with google plugin for eclipse)

class UserData {
    private int _integerval = 0;
    private String _stringval = "";
    public Entity getEntity() {
        Entity ret = new Entity( "User", key );
        ret.setProperty( "property1", _integerval );
        ret.setProperty( "property2", _stringval );
        return ret;
    }

    public static UserData fromEntity( Entity ent ) {
        UserData ret = new UserData();
        ret._integerval = (Integer)ent.getProperty("property1");
        ret._stringval = (String)ent.getProperty("property2");
        return ret;
    }
}

Do I always have to catch this exception like this:

try
{
    ret._integerval = (Integer)ent.getProperty("property1");
}
catch( ClassCastException ex ) {
    Long val = (Long)ent.getProperty("property1");
    ret._integerval = val.intValue(); 
}

Or maybe all the numeric values are stored as long only? Do I have to change _integerval type to long to avoid this exceprion?

like image 676
Dmitry Avatar asked Mar 06 '13 11:03

Dmitry


1 Answers

Use int instead of Integer while casting.

ret._integerval = (int)ent.getProperty("property1");

Edit:

The following is included in the setProperty API.

As the value is stored in the datastore, it is converted to the datastore's native type. This may include widening, such as converting a Short to a Long.

So your int data is being converted to datastore's native type as Long. Cast using long or Long.

like image 121
Jayamohan Avatar answered Oct 24 '22 11:10

Jayamohan