如何在Ebean Java Play中自动添加数据到reference table?

How to automatically add data to reference table in Ebean Java Play?

我有一个 table 多对一关系。然后我尝试通过控制器向数据库添加数据。在我的例子中,有 2 个模型命名为

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 table 中添加数据。它不会将数据添加到 post_text table。我如何使用 E-bean 向两个 table 添加数据?

正在使用 EBEAN 吗?如果是这样,为什么要使用大量代码? 像这样简单地使用添加数据:

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