使用 POJO 将复杂的 JPA 实体传递给控制器
我的团队正在编写一个涉及编辑类似维基百科页面的应用程序。 这与我们在注册时遇到的问题类似:
一个简单的实现给出了类似
public static void doRegistration(User user) {
//...
}
用户参数是 JPA 实体的内容。用户模型看起来像这样:
@Entity
public class User extends Model {
//some other irrelevant fields
@OneToMany(cascade = CascadeType.ALL)
public Collection<Query> queries;
@OneToMany(cascade = CascadeType.ALL)
public Collection<Activity> activities;
//...
我已阅读此处和 失败。现在,在 Play! 中,我们可以采取的最佳行动方案是什么?必须有某种方法将必须发送到服务器的所有数据放入一个对象中,以便可以轻松地将其保存到数据库中。
编辑:失败的原因是验证失败。在验证集合对象时,它以某种方式说“值不正确”。我想知道这是否可以避免。
解决方案:将集合更改为列表已解决该问题。这是一个错误,将在 1.2 版本中修复:)
预先感谢
My team is coding an application that involves editing wikipedia-like pages.
It is similar to the problem we have with registration:
A straightforward implementation gives something like
public static void doRegistration(User user) {
//...
}
The user parameter is a JPA Entity. The User model looks something like this:
@Entity
public class User extends Model {
//some other irrelevant fields
@OneToMany(cascade = CascadeType.ALL)
public Collection<Query> queries;
@OneToMany(cascade = CascadeType.ALL)
public Collection<Activity> activities;
//...
I have read here and there that this fails. Now, in Play!, what is the best course of action we can take? There must be some way to put all that data that has to go to the server in one object, that easily can be saved into the database.
EDIT: The reason this fails is because of the validation fail. It somehow says "incorrect value" when validating collection objects. I was wondering if this can be avoided.
SOLUTION: Changing the Collection to List has resolved the issue. This is a bug that will be fixed in play 1.2 :)
Thanks beforehand
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有效。更清楚地说,您可以定义一个像您编写的那样的控制器方法:
那完全没问题。只需将其映射到 POST 路由并使用 #{form} 提交对象,例如:
这有效。如果您不在表单中添加实体的所有字段(如果某些字段不可编辑,请使用隐藏输入或 NoBinding 注释,如 此处)。
编辑:在 OneToMany 主题上,关系将由“Many”方管理。该方必须将相关实体的 id 保留为隐藏字段(值为 object.user.id)。这将解决所有相关问题。
this works. To be more clear, you can define a controller method like the one you wrote:
That's completely fine. Just map it to a POST route and use a #{form} to submit the object, like:
This works. You may have problems if you don't add all the field of the entity in the form (if some fields are not editable, either use hidden inputs or a NoBinding annotation as described here).
EDIT: on the OneToMany subject, the relation will be managed by the "Many" side. That side has to keep the id of the related entity as a hidden field (with a value of object.user.id). This will solve all related issues.
它不会失败。如果您有运行的交易,那么整个事情将持续存在。请注意,交易通常是在服务内部运行的,而不是控制器,因此您应该将其从控制器传递给服务。
It doesn't fail. If you have a running transaction, the whole thing will be persisted. Just note that transactions are usually running within services, not controllers, so you should pass it from the controller to the service.