我正在尝试使用带有 Morphia 的 MongoDB 作为我的后端数据库,我已经实现了一个实用程序类来简化对数据库的访问。我实现了基本的添加用户功能但是我得到了很多例外:
java.lang.IndexOutOfBoundsException
我放的时候例外
查询 query = datastore.createQuery(User.class).filter("name = ", username);
用于在提交前检查用户。
删除时:我得到这两个例外:
java.lang.RuntimeException: java.lang.NumberFormatException:
如何解决这个问题?
这是我为该项目提供的代码:
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);
}
}
}