1

If I make a domain object in a controller and don't call .save(), Grails will do it for me automatically at some point. I am creating lots of domain objects without planning to save all of them and getting 'references an unsaved transient instance' exceptions when my service exits.

How would I get a list of all objects that Grails will try to save when the controller/service exits so that I could prevent some of them from being saved?

doelleri
  • 19,232
  • 5
  • 61
  • 65
Mikey
  • 4,692
  • 10
  • 45
  • 73

1 Answers1

3

You're better off retrieving instances that you know you will edit but don't want persisted with the read method instead of get. Using read doesn't make it read-only, since if you call save() and it was modified it will be persisted, but it won't be auto-persisted when the OSIV interceptor flushes the session.

Another option (especially if the instance isn't individually loaded) is to remove it from the session using detach() while you're editing it.

You could also use DTOs and copy the data into those non-persistent classes so you're not mucking with persistent classes, just data classes that Hibernate doesn't know about.

Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • I'm talking about objects I make with `new SomeDomainClass()` but then didn't actually want. – Mikey Aug 14 '12 at 00:39
  • Also, based on your "use DTOs" comment can you check out my question: http://stackoverflow.com/questions/11918276/grails-can-i-use-domain-objects-when-i-dont-want-to-save-anything – Mikey Aug 14 '12 at 00:39
  • Burt, I feel like sometimes I come off rude to you, and less than enthusiastic about grails. This could not be farther from how I feel. You rock, thanks for answering so many of my questions. – Mikey Aug 14 '12 at 01:15
  • 1
    New instances are never automatically saved - Hibernate doesn't know anything about them until they're associated with the session, and that only happens when they're attached via a `save()` call. There is cascaded saving with collections when you use `addToFoo`, but I assume that's not what you're talking about. – Burt Beckwith Aug 14 '12 at 04:17