Benefits of object.get() vs object.read() in Grails
Asked Answered
B

1

26

I was skimming some of the Grails documentation and found this bit about the read() method in Grails. If I'm understanding this correctly, you can pull a "read-only" version of an object from the database that will only be saved on an explicit save() call. It seems to me then, that you should use a read() call whenever you have an object that you don't expect to be changed.

But why wouldn't you just always use a read() call? Since the object will be changed to read/write permissions if you save() it anyway, wouldn't it be safer to just read in the object instead of getting it?

Biannulate answered 9/7, 2012 at 18:13 Comment(0)
R
22

You're probably correct - it'd be equivalent in most cases. But Hibernate doesn't require that you call save() since it does dirty checking during a flush and since Grails uses an "Open Session in View" interceptor there will always be a flush at the end of each request. This surprises people who make changes in an instance retrieved by get() that were meant to only be temporary while rendering the view but then the changes get persisted anyway without a save() call. read() would make more sense in that scenario.

One performance optimization is to use http://grails.org/doc/latest/ref/Database%20Mapping/dynamicUpdate.html to only push changed fields to the database. The default is to push all fields whether they're changed or not since then there's no need to generate new SQL for each update. If you read() an instance Hibernate doesn't keep the original data so dynamic update wouldn't be possible since there would be no way to know which fields are dirty.

Rubbing answered 9/7, 2012 at 19:46 Comment(2)
So if you read() and object and make a property change and the entire session gets flushed then that object will not be propagated to the database correct? The object would only get flushed when you explicitly call save() on that instance. Is this correct?Gallbladder
Correct - it basically disables auto-flush, but doesn't disable explicit flushingRubbing

© 2022 - 2024 — McMap. All rights reserved.