struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Greg Lindholm <greg.lindh...@gmail.com>
Subject Re: Prevent persisting data when validation fails
Date Mon, 20 Jul 2009 13:56:51 GMT
> I use JPA (hibernate) to persist.
>
>
>
> An example of action that use prepare to load a person object from
> transactional manager. When the validate fails and it return back to the
> input page the request ends and the transaction persists the dirty user
> object to database. The dirty user object should not be persisted if the
> validation fails.:
>
> public class PersonAction extends BaseAction implements Preparable {
>
> private PersonManager personManager;
> private Person person;
>
> public void prepare() {
>        person = personManager.getPerson(id);
> }
>
> public String savePerson() {
>       manager.savePerson(person);
>       return SUCCESS;
> }
>
> public void validate() {
>       if (person.firstName.length < 5 and person.firstName > 10) {
>           addActionError("Firstname length should be between 5 and 10
> characters.");
>        }
> }
>
> }
>
>
This isn't really a Struts problem, it just the way Hibernate works.

If you make changes to a monitored object (Persistent state) from the
database then Hibernate will detect this and save the changes to the
database when you commit the transaction.  There is actually no need to call
"save" to update a db object it will happen automatically.

To "fix" your problem you have a couple of choices:

1) Don't make changes to db objects unless you are sure you want them
saved.  This would mean changing your actions to work with copies of the
objects or Detached objects instead of the actually db objects (this is what
I do).

2) Don't commit the transaction if the validation fails.  Do a rollback
instead.

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message