mongodb - java.lang.IllegalStateException : Method on class [Domain Class] was used outside of a Grails application 错误

标签 mongodb postgresql grails grails-orm

context.GrailsContextLoaderListener Error initializing the application: Method on class [Domain Class(auth.Role)] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

java.lang.IllegalStateException: Method on class [Domain Class(auth.Role)] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

此异常在这一行抛出:

  def existingRole = Role.findByAuthority(role) // Code Interrupts 

Role.groovy

import org.bson.types.ObjectId

class Role {

   // static mapWith = 'mongo' (For mongoDb we have plugin, so this is working)
   static mapWith = 'none' //(Migrating MongoDB to postgreSql so changed mapWith to 'none')
   ObjectId id
   String authority

   static constraints = {
        authority blank: false, unique: true
   }
}

UserService.groovy

@Transactional
class UserService {

    def grailsApplication

/**
 * Create Users with supplied roles
 * @param usersAndRoles map of user:role
 *
 * @return
 */
def createUsers(def usersAndRoles) {
    // [user:ROLE_USER, manager:ROLE_MANAGER, admin:ROLE_ADMIN]
    // For supplied list of user:role, create user with role
    usersAndRoles.each { key, value ->
        def user = User.findByUsername(key)
        if (!user) {
            def fields = grailsApplication.config."${key}"
            user = new User(username: fields.username,
                    password: fields.password,
                    email: fields.email,
                    passwordExpired: true).save(flush: true)
        }

        // Get the role for this user, set authorities to this role and save
        def role = Role.findByAuthority(value)
        user.authorities = [role]
        user.save(flush: true)
    }
}

/**
 * Create supplied roles
 * @param roles list of roles
 * @return
 */
def createRoles(def roles) {
    roles?.each { role ->
        def existingRole = Role.findByAuthority(role) // Code Interrupts Here
        if (!existingRole) {
            new Role(authority: role).save(flush: true)
        }
    }
}
}

最佳答案

如果你使用

static mapWith = 'none'

它不会将此域类映射到任何数据库,因此无法访问(因为它不是持久的)。将映射添加到任何数据库(它甚至可以是默认的 h2 数据库),它会再次工作。

关于mongodb - java.lang.IllegalStateException : Method on class [Domain Class] was used outside of a Grails application 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34893206/

相关文章:

MongoDB 最大文档大小

java - MongoDB+Java : Credentials missing in the user document

Postgresql:间隔和夏令时问题

python - 在 Sqlalchemy/Postgres 中使用绑定(bind)参数执行 WHERE IN

sql - Postgres pg_trgm GIN 索引在特定连接中被忽略

Grails 获取 hasMany 中的任何子级

angular - 如何使用grails 3和angular创建Web应用程序?

javascript - Mongoose - 如何处理许多错综复杂的关系?下面包含特定的快速挑战示例请求。谢谢

node.js - mongodb/mongoose 查找两个数组中的共同元素

grails - 如何在grails中设置自动增量的起始值