开发者

why read-only access is writing to my db, in GORM?

开发者 https://www.devze.com 2023-04-10 10:43 出处:网络
In my app, I have a code like this: // 1 Foo.get(123).example = \"my example\" // as expected, don\'t change value in db

In my app, I have a code like this:

// 1
Foo.get(123).example = "my example" // as expected, don't change value in db

// 2
Foo.get(123).bars.each { bar ->
    bar.value *= -1 // it's changing "value" field in dat开发者_如何学编程abase!! WHY?
}
  • note: Foo and Bar are tables in my DB

Why is gorm saving in database is second case? I don't have any save() method in code.

Tks


SOLVED: I need to use read() to get a readonly session. (Foo.discard() also works)

Doc: http://grails.org/doc/latest/guide/5.%20Object%20Relational%20Mapping%20%28GORM%29.html#5.1.1%20Basic%20CRUD

(In the first case, I guess I made mistest)


Both should save, so the first example appears to be a bug. Grails requests run in the context of an OpenSessionInView interceptor. This opens a Hibernate session at the beginning of each request and binds it to the thread, and flushes and closes it at the end of the request. This helps a lot with lazy loading, but can have unexpected consequences like you're seeing.

Although you're not explicitly saving, the logic in the Hibernate flush involves finding all attached instances that have been modified and pushing the updates to the database. This is a performance optimization since if each change had been pushed it would slow things down. So everything that can wait until a flush is queued up.

So the only time you need to explicitly save is for new instances, and when you want to check validation errors.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号