问题
In a grails Domain a have implemented the beforeDelete as follow
class Shop {
def beforeDelete() {
Shop.withNewSession {
Client.findAllByShop(this)*.shop = null
}
}
}
But the client shop null value is not persisted to the DB.
If I add a manual session flush
class Shop {
def beforeDelete() {
Shop.withNewSession { s2->
Client.findAllByShop(this)*.shop = null
s2.flush()
s2.clear()
}
}
}
It works, the client shop value are nulled in the db.
Is this a Grails bug or I have misunderstand the documentation? Doesn't withNewSession imply an automatic flush?
回答1:
The documentation (scroll down a bit to the beforeDelete example here) seems to imply that flushing or clearing the session is not required.
Burt Beckwith has also indicated on the Grails mailing list (see thread here) that manual calls to flush() and clear() aren't necessary in a withNewSession closure.
With that said, there does appear to be a bug report (see details here) using withNewSession starting with Grails 2.2.1.
回答2:
withNewSession gets you a new Hibernate session, but it isn't necessarily transactional. It sounds like you want to use withTransaction instead of withNewSession.
来源:https://stackoverflow.com/questions/12750637/grails-withnewsession-does-not-flush