我刚开始使用App Engine,我试图制作一个非常简单的应用程序,它将具有独特名称的Person对象添加到数据存储区。这个对象:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Person {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent
@Unique
private String name;
public Person(String nameIn){
this.name = nameIn;
}
public Long getId(){
return this.id;
}
public void setId(Long idIn){
this.id = idIn;
}
}
此servlet负责在数据存储上保留对象。但在此之前,方法doesUserExist(String)
检查具有相同“name”字段的对象是否存在:
@SuppressWarnings("serial")
public class PersonDatastoreServlet extends HttpServlet {
private static final String PARAM_NAME = "name";
private PersistenceManager pmf = PMF.get().getPersistenceManager();
public void doGet(HttpServletRequest req, HttpServletResponse response)
throws IOException {
String name = req.getParameter(PARAM_NAME);
PrintWriter printWriter = response.getWriter();
try{
if(!doesUserExist(name)) {
Person p = new Person(name);
pmf.makePersistent(p);
response.setContentType("text/html");
printWriter.println("<h1>"+p.getId()+"</h1>");
}
else {
response.setContentType("text/html");
printWriter.println("<p>User already exists</p>");
}
}
catch(Exception e) {
throw new IOException();
}
finally{
pmf.close();
}
}
private boolean doesUserExist(String nameIn) {
Query q = pmf.newQuery(Person.class);
q.setFilter("name == lastNameParam");
q.declareParameters("String lastNameParam");
String name = nameIn;
try{
List<Person> list = (List<Person>) q.execute(name);
if (list.isEmpty()){
return false;
}
else return true;
}
finally{
q.closeAll();
}
}
}
这看起来非常简单,但它无法正常工作。我有一个处理请求的表单。当我第一次运行我的应用程序时,它确实成功创建并保留了一个对象,但是每当我想添加另一个具有不同名称的对象时,我都会收到错误
Error: Server Error
The server encountered an error and could not complete your request.
If the problem persists, please report your problem and mention this error message and the query that caused it.
它表示查询导致问题,但我知道我的查询有什么问题。有人可以帮忙吗?