Search code examples
hibernategrailsgrails-orm

Grails Service throwing Exception "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow ..."


I have a Grails service containing a method

@Transactional
def method(param1, param2, param3, param4) {
    SomeClass obj = new SomeClass(param1: param1, param2: param2, param3: param3, param4: param4)
    obj.save(flush:true, failOnError:true)
}

The method fails silently, even though I provided the "failOnError" parameter. This already took me some time to figure out, so I changed it to:

@Transactional
def method(param1, param2, param3, param4) {
    try {
        SomeClass obj = new SomeClass(param1: param1, param2: param2, param3: param3, param4: param4)
        obj.save(flush:true, failOnError:true)
    } catch (Throwable t) {
        t.printStackTrace()
    }
}

Now, finally, I get to see the error message which is: "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here". This is curious. I always believed "@Transactional" would provide me with a valid Hibernate session. So I am a little at my wits' end here. Does anyone have any idea what the problem might be?


Solution

  • use session.open() before accessing a database and close by specifying explicitly as one solution. And also a good answer detail is Here by Burt Beckwith.

    Please use his example if it helps .

    void deviceDisconnected(String mobileId, String wifiIp){
       try {
          UserMobile.withTransaction { tx ->
             def mobile = Mobile.findByMobileId(mobileId)
             def userMobile = UserMobile.findByMobileAndWifiIp(mobile, wifiIp)
             userMobile.action = Constants.MOBILE_STATUS_DISCONNECTED
             userMobile.alarmStatus = Constants.ALARM_STATUS_TURNED_ON
             userMobile.modifiedDate = new Date()
             userMobile.save(flush: true)
          }
       }
       catch(e) {
          e.printStackTrace()
       }
    }