我正在尝试设置一个标记库来检查用户是否购买了产品。然而,当我的taglib运行时,我得到了以下错误:
ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[grailsDispatcherServlet] - Servlet.service() for servlet [grailsDispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.grails.gsp.GroovyPagesException: Error processing GroovyPageView: [views/derbypro/index.gsp:124] Error executing tag <g:ifPurchased>: failed to lazily initialize a collection of role: website.User.purchasedProducts, could not initialize proxy - no Session] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: website.User.purchasedProducts, could not initialize proxy - no Session
以下是我的标记库:
package website
class PurchasedProductTagLib {
def ifPurchased = { attrs, body ->
if (!session.user) return
if (Product.findById(attrs.product) in session.user.purchasedProducts) { // <-- error here
out << body()
}
}
def ifNotPurchased = { attrs, body ->
if (!(Product.findById(attrs.product) in session.user?.purchasedProducts)) {
out << body()
}
}
}
这是我的用户域类:
package website
import org.mindrot.jbcrypt.BCrypt
class User {
String username
String passwordHash
String email
static hasMany = [purchasedProducts: Product]
User(String username, String password, String email) {
this.username = username;
passwordHash = BCrypt.hashpw(password, BCrypt.gensalt())
this.email = email
}
}
这似乎只在登录后发生,如果用户注册(并重定向回此页面),则不会发生此错误。
如果有什么作用的话,我将标记库嵌套在一起。