我对Java还比较陌生,正在使用Play框架开发一个基于web的项目。这是一个很好的学习经验,我已经能够找到解决大多数问题的方法,但我坚持保存一个模型到数据库。
我使用的是框架版本2.3.4,在本地运行postgresql数据库。连接很好,但是当我在对象(报纸)上使用.save()方法时,会保存一条空白记录,其中只有ID字段有任何数据。表单中的值似乎被请求绑定得很好。为什么不能保存?
我一直在寻找答案,但似乎没有人有这个问题。
我注意到序列生成的ID并不总是使用下一个数字(跳过20个左右),即使我在本地运行并且是唯一的用户??这可能是某人的线索。。。
模型如下:
package models;
import java.util.*;
import javax.persistence.*;
import play.mvc.*;
import play.db.ebean.Model;
import play.data.validation.*;
/**
* Newspaper entity managed by Ebean
*/
@Entity
public class Newspaper extends Model {
private static final long serialVersionUID = -4004723260163933009L;
@Id
@GeneratedValue(generator="newspaper_seq")
@SequenceGenerator(name="newspaper_seq", allocationSize=1)
public Long id;
public String name;
public Long rate;
/**
* Generic query helper for entity Newspaper with id Long
*/
public static Model.Finder<Long,Newspaper> find = new Model.Finder<Long,Newspaper>(Long.class, Newspaper.class);
public static Map<String,String> options() {
LinkedHashMap<String,String> options = new LinkedHashMap<String,String>();
for(Newspaper c: Newspaper.find.orderBy("name").findList()) {
options.put(c.id.toString(), c.name);
}
return options;
}
}
我的控制器类:
package controllers;
import play.*;
import play.mvc.*;
import views.html.*;
import models.Newspaper;
//import play.api.data.Form;
import play.data.Form;
public class Application extends Controller{
/**
* @param args
*/
public static Result index() {
return ok(views.html.index.render("list of newspapers"));
}
public static Result addNewspaper() {
Form<Newspaper> form = Form.form(Newspaper.class).bindFromRequest();
//return ok(form.toString());
if(form.hasErrors()) {
return badRequest("something didn't work");
}
String oldForm = form.toString();
Newspaper paper = form.get();
paper.save();
// checking value return ok(oldForm + "\n" + form.toString() + "\n" + paper.toString());
return redirect(routes.Application
.index());
}
}
下面是我创建表的SQL(第一次使用postgresql,所以这可能是错误的)
create table newspaper (
id bigint not null,
name varchar(255),
rate bigint,
constraint pk_newspaper primary key (id))
;
create sequence newspaper_seq;
谢谢你抽出时间!
---更新---
我启动了sql调试,在终端中看到了这个错误:
[debug] c.j.b.PreparedStatementHandle - insert into newspaper (id, name, rate) values (101,'[SQL NULL of type 12]','[SQL NULL of type -5]')
出于某种原因,值为空(不同类型?),但是当我输出窗体的
.toString
值时,它似乎显示了正确的数据:Form(of=class models.Newspaper, data={name=Toledo Blade, rate=10}, value=Some(models.Newspaper@2df64761), errors={})
有什么理由不把数据传给报纸模型吗?
最佳答案
好吧-我在another question上找到了答案。我想我用的搜索词不对:(
无论如何,我必须从终端的项目目录中键入activator clean
。在那之后一切都很顺利。希望这能挽救别人几个小时的沮丧!