Domanda

I have a controller, inside the controller I pass the Domain Object to a service to check a version and some other logic. My controller/service call is message = service.updateExisting(domainObj, un, other).

When I run domainObj.version in the controller I get a version lower than when I run it in the service. Also the changes are persisted regardless of the checks I do in the updateExisting method.

I have also tried setting grails.gorm.autoFlush = false in the Config.groovy and def transactional=false in the service neither seems to help. can anyone see what I am missing?

I also tried static transactional=false in the controller and in the service

È stato utile?

Soluzione

I found my answer here. It turns out that the controller ends its Hibernate session when it calls the service persisting the data. If I do the following...

domainObj.discard()
message = service.updateExisting(domainObj, un, other)

This was a little counter-intuitive for me because I thought the discard would discard the changes as well but that doesn't seem to be the case. I then call the .save() in the service and everything persists as expected. Thanks to everyone for trying to help out.

Altri suggerimenti

If you want to prevent automatic flushing for just one situation, try changing the flush mode explicitly for the current session and then switching it back to auto after.

def sessionFactory //inject the service

def doSomethingWithoutFlushing(){
    sessionFactory.currentSession.setFlushMode(org.hibernate.FlushMode.MANUAL)
    def message = service.updateExisting(domainObj, un, other)
    sessionFactory.currentSession.setFlushMode(org.hibernate.FlushMode.AUTO)
}

I would investigate the .read() method as opposed to using .get() - http://www.grails.org/doc/latest/ref/Domain%20Classes/read.html. (Assuming you're using .get() currently.)

That way unless you explicitly call .save() on your domain it won't persist changes and is perhaps a bit nicer/cleaner than calling .discard() before passing the object to the service.

In reviewing the doc just now I didn't realize that any collections on the object will still be automatically saved if modified. So, depending on the complexity of your object and what else is happening in your controller action this may or may not be useful for you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top