我有一张多对一关系的桌子。然后我尝试通过控制器将数据添加到数据库。在我的例子中,有两个名为
的模型Post.java
@OneToMany(mappedBy = "post")
private List<PostText> postBody;
PostText.java
@ManyToOne(fetch = FetchType.LAZY)
@JoinTable(name="post")
@JoinColumn(name = "post_id", referencedColumnName = "post_id")
@NotNull
private Post post;
要插入我尝试过的数据,
@BodyParser.Of(BodyParser.Json.class)
public Result add() {
JsonNode jsonNode = request().body().asJson();
User user = userDAO.findByUsername(jsonNode.findPath(StringLiterals.USERNAME_KEY).textValue());
if (user == null) {
return badRequest(JSONService.toJsonNode(new ResponseWrapper<>(
jsonNode.findPath(StringLiterals.USERNAME_KEY).textValue()
.concat(ResponseMessages.USER_NOT_FOUND), null)));
}
Transaction transaction = Ebean.beginTransaction();
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Post post = objectMapper.treeToValue(jsonNode, Post.class);
post.setUser(user);
// Use JDBC batch API with a batch size of 100
transaction.setBatchSize(4);
// Don't bother getting generated keys
transaction.setBatchGetGeneratedKeys(false);
// Skip cascading persist
transaction.setPersistCascade(false);
postDao.add(post);
this.post = post;
Ebean.commitTransaction();
return ok("Done");
} catch (IOException e) {
return badRequest(e.getLocalizedMessage());
} finally {
Ebean.endTransaction();
}
}
这仅适用于仅在post
表中添加数据。它不会向post_text
表添加数据。如何使用E-bean向两个表添加数据?
答案 0 :(得分:0)
正在使用EBEAN吗?如果是这样,为什么要使用大量代码? 使用Add Data就像这样:
public Result save() {
Form<Computer> computerForm = formFactory.form(Computer.class).bindFromRequest();
if(computerForm.hasErrors())
{return badRequest(views.html.computers.createForm.render(AuthorisedUser.findByEmail(request().username()), computerForm));}
try
{
Computer computerData = computerForm.get();
Computer computer = new Computer();
computer.name = computerData.name;
computer.active = computerData.active;
computer.status = computerData.status;
computer.introduced = computerData.introduced;
computer.save();
flash("success", "Computer [ " + computerForm.get().name + " ] has been created");
return GO_HOME;
}
catch (Exception e)
{
Logger.error("add.computer.save error", e);
flash("erreur", "Computer [ " + computerForm.get().name + " ] has not been created");
}
return GO_HOME;
/*String refererUrl = request().getHeader("referer");
return redirect(refererUrl);*/
}