robinbuehler robinbuehler - 1 year ago 77
Java Question

How do I correctly save a google user in google datastore using objectify?

I try to store a Google User ( inside of an own class in google datastore using objectify. I am using objectify (com.googlecode.objectify) version 5.0.3 and (com.sappenin.objectify) version 5.0.2. This is my class:

public class UserTest {
public Long id;
public User user;
public UserTest() {}
public UserTest(User user) {
this.user = user;

Now I try to store an object of this class using the following servlet class:

import static OfyService.ofy;
public class UserStoreTestService {
public User saveUser() {
Key<UserTest> key = ofy().save().entity(new UserTest(getUser())).now();
UserTest userTest = ofy().load().key(key).now();
return userTest.user;

public User loadUser() {
UserTest userTest = ofy().load().type(UserTest.class)
.filter("user", getUser()).first().now();
return userTest.user;

private User getUser() {
return UserServiceFactory.getUserService().getCurrentUser();

My ofy service looks like that:

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
public class OfyService {
static {
public static Objectify ofy() {
return ObjectifyService.ofy();

When I do a POST request i get this JSON code:


When I do a GET request after the POST I get this JSON code:


The first Id is 18580476422013912411 the second one is -1405876145.

What am I doing wrong?

Answer Source

According to this question, App Engine's datastore can store numbers up to 9,223,372,036,854,775,807 (unsigned long limit). The userId is bigger, hence your issue.

You should store your userId in a String. Anyway, you will not perform any numeric operation on it I assume (comparison, addition, division...).

Here a quick workaround would be to store the userId as String in your custom UserTest class, and accept that the userId in the user attribute will be wrong.

Another option would be to use the @Serialize annotation to store your User object in serialized mode. That way the long will remain untouched.

But more generally, you should not try to store classes that you do not control, because you will end up with issues like this. Here you're unable to convert the userId to a String, but you will also have issues if Google decides to updates its User class later.

Instead you should rather create your own MyUser class and manipulate it. Of course the downside is that you'll have to copy data from the original object to your custom one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download