Search code examples
grailsgrails3

how to make first column nullable in one to many relationship join table?


There seems to be a change in behavior from grails 2 to grails3. When i create a one to many relationship like

class Author {
    static hasMany = [books: Book]
    String name
}
class Book {
    String title
}

It will create a join table with columns author_books_id and book_id. In grails 3 it also adds a not null constraint on the first column. In grails 2 not null constraint is not applied. So when i upgrade to grails 3 it is breaking because there are already few records that have first column values to null. It works fine in grails 2 but with grails 3 the first column should not be null. Furthermore the join table is read only so i cannot remove the rows will null first column values. Is there a way to make the first column nullable = true by making changes in domains and not directly in migration file.

The code was extracted from the grails documentation. Please scroll down to one to many section.

6.2.1.2 One-to-many

http://docs.grails.org/3.0.17/guide/GORM.html


Solution

  • Try changing your Book class to this

    class Book {
        String title
        Author author     // this creates the belongs to relationship
    }
    
    static constraints = {
         author nullable:true
    }
    

    Also when you recompile the code make sure to delete previous table and start fresh. Grails will not alter any table to delete anythings. It only adds new stuffs.