views:

103

answers:

1

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)?

+2  A: 

What is the way to avoid writing an object with illegal state to the database? Roll back the unit of work?

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, and PreRemove 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.

Pascal Thivent
To add to the answer, I'm pretty sure jpa (or hibernate) had some very specific warnings against using data validation in setters. Something along the lines "how we initialize object before it's returned is our own business and setter could be called more than once".
Nikita Rybak