开发者

Id generation problem in Grails when using Oracle and H2 for the same application

I am working on grails application. I must use H2 for development and Oracle for testing and production. I must use separate sequences for each domain class/table when using Oracle so I used the following in my domain classes:

    static mapping = {
       id (generator:'sequence', params:[sequence:'SOME_SEQUENCE'])
    }

But then I am not able to use H2. I get Unique index or primary key violation err开发者_开发知识库or when I try to create new using user interface.

What can be done to have such mapping to work only for production and testing environments and leave defaults for development? I use Grails 1.3.7.


I had the same problem. You can also solve this by creating the sequences in h2 with environment-specific settings in your BootStrap.groovy file. In my case, I didn't have too many sequences that I needed to integration test and I didn't want to clutter up my domain classes with environment-specific coding. Here is my BootStrap. This worked fine for me:

import groovy.sql.Sql

class BootStrap {
    def dataSource
    def init = { servletContext ->

        environments {
            test {
                Sql sql = new Sql(dataSource)
                sql.execute("create sequence if not exists SOME_SEQUENCE")
            }
        }

    }
}


You can embed logic inside the mapping block for cases like this:

import grails.util.Environment

class MyDomainClass {
   ...
   static mapping = {
      if (!Environment.isDevelopmentMode()) {
         id (generator:'sequence', params:[sequence:'SOME_SEQUENCE'])
      }
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜