How to use Morphia with Java / GWT

573 views
Skip to first unread message

Xybrek

unread,
Aug 6, 2011, 4:38:55 AM8/6/11
to Morphia
I am trying to use MongoDB with Morphia as my back-end DB, I have
implemented a utility class to simplify access to the database. I
implemented basic add user function with However I am getting `lots of
exceptions:

java.lang.IndexOutOfBoundsException exception when I put

Query query = datastore.createQuery(User.class).filter("name = ",
username);

for checking user before comitting.

When removed: I get these two exceptions:

java.lang.RuntimeException: java.lang.NumberFormatException:
How to fix this issue?

Here are the code I have for the project:

MorphiaUtil.java:
public class MorphiaUtil {

protected final Log log = LogFactory.getLog(getClass());
private static Mongo mongo;
private static Datastore datastore;

static {
try {
// Create the database connection
mongo = new Mongo("localhost");
datastore = new Morphia().createDatastore(mongo,
"mygwtapp");
} catch (UnknownHostException e) {
System.err.println("Caught Unknown host exception:"+e);
e.printStackTrace();
} catch (MongoException e) {
System.err.println("Initial Datastore creation
failed:"+e);
e.printStackTrace();
}
}

public static Datastore getDatastore() {
return datastore;
}
}
UserServiceImpl.java

public class UserServiceImpl extends RemoteServiceServlet
implements UserService {
@Override
public void addUser(String username, String password)
throws IllegalArgumentException {
try {
Datastore datastore = MorphiaUtil.getDatastore();
Query query =
datastore.createQuery(User.class).filter("name = ", username);
User user = (User) query.asList().get(0);
if (user == null) {
user = new User(username, password);
datastore.save(user);
}

} catch (Exception e) {
System.err.print("Caught exception:"+e);
}
}
}

Scott Hernandez

unread,
Aug 6, 2011, 8:30:46 AM8/6/11
to mor...@googlegroups.com
Please include the full stack-trace and code for User.

Michael Weinberg

unread,
Aug 6, 2011, 11:14:17 AM8/6/11
to Morphia
It's pretty obvious that you get java.lang.IndexOutOfBoundsException
because when the user doesn't exist the query returns an empty list,
but instead of checking whether it's empty you always try to fetch the
first element by doing ".get(0)", thus causing the
IndexOutOfBoundsException.

Scott Hernandez

unread,
Aug 6, 2011, 11:20:34 AM8/6/11
to mor...@googlegroups.com
In fact, Query (QueryResult) has a get() method which will return the
first, or null.

User user = query.get();

Reply all
Reply to author
Forward
0 new messages