如何在Ebean Java Play中自动将数据添加到引用表?

时间:2016-06-09 14:25:17

标签: java playframework-2.0 ebean

我有一张多对一关系的桌子。然后我尝试通过控制器将数据添加到数据库。在我的例子中,有两个名为

的模型

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向两个表添加数据?

1 个答案:

答案 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);*/
    }