重用验证作为数据库约束
我正在使用 Play!框架并在编写测试时发现我可以保存无效的模型实例,例如某些实例变量的值无效。我想这是将验证和持久性分开的预期行为。但是有没有办法重用验证注释作为数据库约束呢?
I'm using the Play! framework and discovered while writing tests that I can save an invalid model instance, e.g. with invalid values for some instance variables. I guess that's expected behaviour to keep validation and persistence separated. But is there any way to reuse the validation annotations as database constraints?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对Play一无所知。您使用 JSR 303 验证注释吗?根据 Play 文档,它可以/确实使用 Hibernate 进行持久化。从 Hibernate 3.5 开始, Hibernate 将包括约束通过其生成的架构中的 JSR 303 注释来表达。
I don't know anything about Play. Do you use JSR 303 validation annotations? According to the Play documentation, it can/does use Hibernate for persistence. As of Hibernate 3.5, Hibernate will include constraints expressed via JSR 303 annotations in the schema it generates.
不,验证与数据库约束无关。您必须通过 SQL 在数据库中手动添加约束,例如使用新的 evolutions Play 1.2.1 框架。
在单元测试中,您必须确保数据正确。在任何情况下,您应该只测试模型中的逻辑,类之间没有依赖关系,只需做一些测试来检查可以使用意外参数的地方的答案,但不必担心使用错误数据保存的实例。
在集成测试和 selenium 测试中,您应该能够通过控制器调用上的 @Valid 使用 Play 提供的验证系统。您应该在此处确保不保留任何具有错误数据的对象,并尝试添加一些对象。
No, the validation is not linked to database constraints. You have to add the constraints manually in the database via SQL, for example using the new evolutions framework of Play 1.2.1.
In your unit tests you must ensure the data you is correct. At any case you should only be testing logic in the Model, no dependencies between classes, just do some tests to check answer to unexpected parameters in places where they could be used but don't worry about instances saved with wrong data.
In your integration tests and selenium tests you should be able to use the Validation system provided by Play via @Valid on controller calls. Here is where you should ensure no objects with bad data are persisted, trying to add some.