2016-06-09 34 views
0

我有一個表與多對一的關係。然後我嘗試通過控制器將數據添加到數據庫。在我的情況下,有2種型號命名,如何自動將數據添加到Ebean Java Play中的引用表中?

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(); 
    } 
} 

這隻適用於添加da ta只在post表中。它不會將數據添加到post_text表中。如何使用E-bean將數據添加到兩個表中?

回答

0

正在使用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);*/ 
    } 
相關問題