Grails 2.4.4,多个数据源,在Domain类上使用GORM finder导致:类[User]上的方法在Grails应用程序之外使用

时间:2015-03-21 09:11:00

标签: grails

我试图在BootStrap.groovy init闭包中输入默认用户。它导致了这个错误: 类[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))
   }
}

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

runtime ":hibernate4:4.3.6.1"

我在另一个Grails应用程序中做了类似的事情,使用相同版本的Grails和Hibernate,并且这个工作正常。我能看到的两个不同之处是:

  1. 我没有使用多个数据源
  2. 正在运行的应用程序使用服务创建默认用户,该用户将注入BootStrap.groovy文件。
  3. 我不确定我在这里做错了什么,或者如何解决它。

    非常感谢任何帮助。

    感谢。

1 个答案:

答案 0 :(得分:2)

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

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

因此,只需将您的数据源名称从adminDataSource更改为dataSource_adminDataSource