Search code examples
grailsgrails-orm

GORM adding rows in an order that is the reverse of the order they were added


class Dog {
    String name
    String type

    static hasMany = [snacks:Snack]
}


class Snack {
    String name;
    String protein;
    Boolean vegetarian;     
}

dogInstance.addToSnacks(new Snack(name: "Dog Yums", protein: "Pork", vegetarian: false);
dogInstance.addToSnacks(new Snack(name: "Super Tasty Snack", protein: "Beef", vegetarian: false);
dogInstance.addToSnacks(new Snack(name: "Woofles", protein: null, vegetarian: true);
dogInstance.save(flush: true)

I expect the database table for snacks to have the snack entries in the order they were added. Instead, they end up reversed in the database. Any idea why this is happening? I am using an MSSQL database to store the data.

What I Except

id: 1, name: Dog Yums, protein: Pork, vegetarian: False

id: 2, name: Super Tasty Snack, protein: Beef, vegetarian: False

id: 3, name: Dog Yums, protein: null, vegetarian: True

What I Get

id: 1, name: Dog Yums, protein: null, vegetarian: True

id: 2, name: Super Tasty Snack, protein: Beef, vegetarian: False

id: 3, name: Dog Yums, protein: Pork, vegetarian: False


Solution

  • By default GORM (Hibernate actually) does not guarantee the order of the collection. If you need the collection to be in a specific order you will need to specify this collection as a List<T> such as:

    class Dog {
        String name
        String type
        List<Snack> snacks
    
        static hasMany = [snacks:Snack]
    }