Defining Grails Domain ID in Bootstrap.groovy

Is it possible to explicitly specify the id of a domain object in Bootstrap.groovy Grails (or anywhere, for that matter)?

I tried the following:

new Foo(id: 1234, name: "My Foo").save()

and

def foo = new Foo()
foo.id = 1234
foo.name = "My Foo"
foo.save()

But in both cases, when I print the results Foo.list()at runtime, I see that my object is assigned identifier 1 or any next identifier in the sequence.

Edit: This is in Grails 1.0.3, and when I run my application in "dev" with the built-in HSQL database.

Edit: chanwit provided one good solution below . However, I was really looking for a way to set the identifier without changing the method of generating the domain identifier. This is primarily for testing: I would like to be able to set certain things in the values ​​of known identifiers either in my test bootstrap or in setUp(), but still be able to use auto_increment or sequence in the production process.

+3
source share
3 answers

Yes, with GORM displaying manually:

class Foo {
  String name
  static mapping = {
    id generator:'assigned'
  }
}

and your second fragment (not the first) will complete the task (Id will not be assigned when passing it through the constructor).

+10
source

, , , . , , , :

class Foo {
  short code /* new field */
  String name

  static constraints = {
    code(unique: true)
    name()
  }
}

enum ( ) Foo, Foo.findByCode() ( Foo.get() id, ).

, .

+1

Alternatively, assuming that you are importing data or transferring data from an existing application , you can use local maps in the Bootstrap file for testing purposes. Think of it as import.sql with benefits; -)

Using this approach:

  • you don’t need to change the domain restrictions for testing purposes only,
  • you will have a proven migration path from existing data and
  • you will have a good data slice (or full snippet) for future integration tests

Hurrah!

def init = { servletContext ->

    addFoos()
    addBars()

}

def foosByImportId = [:]
private addFoos(){
    def pattern = ~/.*\{FooID=(.*), FooCode=(.*), FooName=(.*)}/
    new File("import/Foos.txt").eachLine {
        def matcher = pattern.matcher(it)
        if (!matcher.matches()){
            return;
        }

        String fooId = StringUtils.trimToNull(matcher.group(1))
        String fooCode = StringUtils.trimToNull(matcher.group(2))
        String fooName = StringUtils.trimToNull(matcher.group(3))

        def foo = Foo.findByFooName(fooName) ?: new Foo(fooCode:fooCode,fooName:fooName).save(faileOnError:true)
        foosByImportId.putAt(Long.valueOf(fooId), foo) // ids could differ
    }
}

private addBars(){
    ...
    String fooId = StringUtils.trimToNull(matcher.group(5))
    def foo = foosByImportId[Long.valueOf(fooId)]
    ...
}
+1
source

Source: https://habr.com/ru/post/1702484/


All Articles