Do I ever need to explicitly flush GORM save calls in grails?

前端 未结 4 1963
说谎
说谎 2020-12-04 12:25

I have a strange situation which appears to indicate a GORM cacheing problem

//begin with all book.status\'s as UNREAD
Book.list().each { book.status = Statu         


        
4条回答
  •  一整个雨季
    2020-12-04 13:06

    In your case, the first statement return empty list because it reads data from the database, but the data isn't there yet.

    It's how Hibernate works: When you call save with (flush: true), it will flush the Hibernate session, persistent all data in session to database immediately. If not using (flush:true), the data is only recorded in Hibernate session and only get persisted in database when Hibernate session is flushed. The time to flush the session is automatically determined by Hibernate to optimize the performance.

    Generally, you should let Hibernate do the work for you (for optimization sake) - unless you want the data are persisted right away.

    According to Peter Ledbrook:

    Let Hibernate do it's job and only manually flush the session when you have to, or at least only at the end of a batch of updates. You should only really use if you're not seeing the data in the database when it should be there. I know that's a bit wishy-washy, but the circumstances when such action is necessary depend on the database implementation and other factors.

    From GORM Gotchas - part 1

    UPDATE: to be clear about how to flush the session one time after all the object get saved:

    import org.hibernate.*
    
    class SomeController {
      SessionFactory sessionFactory
    
      def save = {
        assert sessionFactory != null
    
        // loop and save your books here
    
        def hibSession = sessionFactory.getCurrentSession()
        assert hibSession != null
        hibSession.flush()
      }
    }
    

提交回复
热议问题