简体   繁体   中英

grails getting lazzy initialization exception in transactional service

I'm getting a typical hibernate Lazy initialization exception in my transactional service while accessing propert of an object of a SET.

org.hibernate.LazyInitializationException: could not initialize proxy - no Session


class ProductService {
  static transactional = true
  def xyz() {
    def products = Product.list()
    products.each { product ->
      def category = product.categories.asList().first()
      def title = category.title
    }
  }
}

I'm getting exception when accessing the title property of category

xyz is a Closure being invoked by Groovy as if it were a method, but it's not a method. So it's not proxied by Spring (it's just a field), and you get no transactional behavior. There's almost never a good reason to have a public closure in a Service class (inner utility closures are fine).

This should work:

void xyz() {
   for (product in Product.list()) {
       def category = product.categories.asList().first()
       def title = category.title
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM