工作单元模式的验证策略
当我使用 工作单元模式(使用 JPA)时,我从存储库获取一个实体,修改它并将工作单元的修改隐式保存到数据库中。
现在我想知道如何使用工作单元模式执行验证。如果我将更改(来自用户输入)应用于域对象并随后进行验证,即使验证失败,该对象的值也会发生更改。如何避免将非法状态的对象写入数据库?回滚工作单元?
OOP 的目标之一是对象监视自己的状态,以便它们永远不会接受非法值。对于这种方法,我必须抛出异常,这与上面的 bean 验证(和 spring 验证)方法相反。但也许它更简单、更好。
您将使用什么验证策略(在领域驱动设计中)?
When I use the unit of work pattern (with JPA), I get an entity from a repository, modify it and save the modifications at the and of the unit of work implicitly to the database.
Now I wonder how to perform validation with the unit of work pattern. If I apply changes (from user input) to a domain object and validate after that, the values of that object would be changed even if validation fails. What is the way to avoid writing an object with illegal state to the database? Roll back the unit of work?
One of the goals of OOP is that objects watch over their own state, so that they never accept illegal values. For this approach I had to throw exceptions and it is the opposite of the bean validation (and spring validation) approach from above. But maybe it is simpler and better.
What validation strategy would you use (in domain driven design)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 Bean Validation API,它将抛出异常并且更改不会被持久化(如果启用,验证应该在
PrePersist
、PreUpdate
的最后阶段进行code> 和PreRemove
生命周期事件)。使用 JPA 2.0,只需将 Bean Validation 实现放在类路径上即可。
对于 JPA 1.0,请参阅之前的答案。
If you use the Bean Validation API, it will throw an Exception and changes won't be persisted (if enabled, validation is supposed to occur at the final stage of the
PrePersist
,PreUpdate
, andPreRemove
lifecycle events).With JPA 2.0, just put a Bean Validation implementation on the class path.
With JPA 1.0, refer to this previous answer.