Grails 2.4.4,多个数据源,在域 class 上使用 GORM 查找器导致: class [User] 上的方法在 Grails 应用程序之外使用

Grails 2.4.4, Multiple DataSources, Using GORM finder on Domain class results in: Method on class [User] was used outside of a Grails application

我正在尝试在 BootStrap.groovy init 闭包中添加默认用户。它导致了这个错误: class [com.exmaple.AdminUser] 上的方法在 Grails 应用程序之外使用。

我的 BootStrap.groovy 文件:

class BootStrap {
   def init = { servletContext ->
      if (!AdminUser.findByEmail("eric@example.com")) {
         AdminUser eric = new AdminUser(
               email: "eric@exmaple.com",
               firstname: "Eric",
               lastname: "Berry",
               password: "password"
         ).save()
         if (eric.hasErrors()) {
            log.error("Error creating admin user: ${eric.errors}")
         }
      }
   }
   def destroy = {
   }
}

我的 DataSource.groovy 文件(相关位):

dataSources {
   dataSource {
      ...
   }
   adminDataSource {
      pooled = true
      jmxExport = true
      driverClassName = "org.h2.Driver"
      username = "sa"
      password = ""
   }
}
hibernate {
   cache.use_second_level_cache = false
   cache.use_query_cache = false
   cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
   singleSession = true // configure OSIV singleSession mode
}

// environment specific settings
environments {
   development {
      dataSources {
         dataSource {
            ...
         }
         adminDataSource {
            dbCreate = "update"
            url = "jdbc:h2:admin_user_db;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
         }
      }
   }
}

我的 AdminUser 对象:

class AdminUser {
   String id
   Date dateCreated
   Date lastUpdated

   String email
   String firstname
   String lastname
   String password

   static constraints = {
      id(maxSize: 36)
      email(nullable: false, blank: false, email: true, unique: true)
      firstname(nullable: false, blank: false)
      lastname(nullable: false, blank: false)
      password(nullable: false, blank: false)
   }

   static mapping = {
      datasource('adminDataSource')
      id(generator: 'uuid2')
   }

   def beforeInsert() {
      encodePassword()
   }

   def beforeUpdate() {
      if (isDirty('password')) {
         encodePassword()
      }
   }

   private void encodePassword() {
      password = BCrypt.hashpw(password, BCrypt.gensalt(12))
   }
}

最后,我的休眠版本是(来自BuildConfig.groovy):

runtime ":hibernate4:4.3.6.1"

我正在另一个 Grails 应用程序中做类似的事情,使用相同版本的 Grails 和 Hibernate,并且那个工作正常。我可以看到的两个区别是:

  1. 我没有使用多个数据源
  2. 正在运行的应用程序使用服务创建默认用户,该用户被注入到 BootStrap.groovy 文件中。

我不确定我做错了什么,或者如何解决它。

如有任何帮助,我们将不胜感激。

谢谢。

这是因为您在 DataSource.groovy 文件中使用了错误的数据源名称 (adminDataSource)。

在多数据源中,所有数据源名称都必须有前缀 dataSource_,默认数据源除外。

所以只需将您的数据源名称从 adminDataSource 更改为 dataSource_adminDataSource