Modify and validate a grails domain object without saving it
Asked Answered
G

1

7

How do I use the GORM .get to retrieve an object o, modify some fields, and call o.validate() to find errors without Hibernate saving the object to the DB. discard by itself does not prevent the save. Neither does

                clazz.withTransaction { status ->
                  row.validate(flush:false)
                  row.discard()
                  status.setRollbackOnly()
                }

This post recommend using a command object but this code will apply to many different domain object. There must be a simple way (some parameter passed to validate?) to give Hibernate the do not save instruction. Do I need to create a new instance every time?

Goldfinch answered 12/10, 2011 at 19:36 Comment(0)
A
11

If you use read() instead of get() to retrieve the object it won't be auto-saved during a flush (e.g. at the end of a transaction or a web request). It's not truly read-only, since you can call save() and it will persist - it's just not going to auto-save when dirty.

Anthropomorphism answered 12/10, 2011 at 20:48 Comment(2)
isn't it necessary to call o.save() explictly to put an object in the flush queue?Shep
No, any instance attached to the session that's modified will be flushed. The only time you need to call save() is for new instances.Anthropomorphism

© 2022 - 2024 — McMap. All rights reserved.