Reputation: 35276
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);
}
}
}
Upvotes: 5
Views: 2570
Reputation: 1063
I created a server version of all my beans, and before calling saving methods, i convert from Simple Beans (used in client side) to MorphiaBeans (used only for morphia operations).
That's not the best method to fix this issue, but works fine for me!
Upvotes: 2