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將數據添加到兩個表中?