Terafin
Terafin

Reputation: 1

How to set an 'int' Java model property to its original unset state rather than to zero in the App Engine datastore?

One of the properties of my Java model class representing a datastore entity, is represented by an int value:

int trackedUserId;

This value is set to a particular user id during the course of the app's execution. And then at other points I want to reset it to its original unset state represented by a null value. But the only way I can see to reset it is to set it to a value of zero. Is there some other way in JDO to reset a property to its unset state?

Upvotes: 0

Views: 2257

Answers (2)

MirroredFate
MirroredFate

Reputation: 12816

Integer trackedUserId;
trackedUserId = 1;
//voodoo happens
//so you reset to null
trackedUserId = (Integer) null;

Like you said, its original state is represented by a null value, so if you want it to be null again, simply set it as such.

Upvotes: 0

Nick Johnson
Nick Johnson

Reputation: 101139

int is a primitive value, so it can't be set to null. Per the JDO docs, here:

If a datastore entity is loaded into an object and doesn't have a property for one of the object's fields and the field's type is a nullable single-value type, the field is set to null. When the object is saved back to the datastore, the null property becomes set in the datastore to the null value. If the field is not of a nullable value type, loading an entity without the corresponding property throws an exception. This won't happen if the entity was created from the same JDO class used to recreate the instance, but can happen if the JDO class changes, or if the entity was created using the low-level API instead of JDO.

If you're creating a new record which has an int field, and don't specify a value, it will have Java's default value for such fields, which is 0.

Upvotes: 4

Related Questions