[英]How to automatically add data to reference table in Ebean Java Play?
I have a table with many to one relationship. 我的桌子有多对一的关系。 Then I tried to add data through the controller to the database.
然后,我尝试通过控制器将数据添加到数据库。 In my case there are 2 models named,
在我的案例中,有2种型号
Post.java Post.java
@OneToMany(mappedBy = "post")
private List<PostText> postBody;
PostText.java PostText.java
@ManyToOne(fetch = FetchType.LAZY)
@JoinTable(name="post")
@JoinColumn(name = "post_id", referencedColumnName = "post_id")
@NotNull
private Post post;
To insert the data I tried, 要插入我尝试过的数据,
@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();
}
}
This works only for add data only in post
table. 这仅适用于仅在
post
表中添加数据。 It doesn't add data to the post_text
table. 它不会将数据添加到
post_text
表中。 How may I add data to both 2 tables using E-bean? 如何使用E-bean将数据添加到两个表中?
Are using EBEAN ? 正在使用EBEAN吗? if so, why are using lot of code ?
如果是这样,为什么要使用大量代码? to use Add Data simply something like this :
使用添加数据只是这样的事情:
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);*/
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.