Search code examples
grailsgrails-ormgrails-3.1

Grails 3.1 - Multiple inserts into domain


When adding a single Book, you can just do:

String author = 'John Smith'
String title = 'First Book'
def book = new Book(author: author, title: title)
book.save(flush: flush, insert: true)

Say I want to add a number of books at once, for instance if the input is:

String author = 'John Smith'
String title = ['First Book', 'Second Book', 'Third Book']

How can I save all the books with one call to the database?


Solution

  • A Groovy SQL Solution:

    def author = 'John Smith'
    def titles = ['First Book', 'Second Book', 'Third Book']
    
    def bookClassMetadata = sessionFactory.getClassMetadata(Book)
    
    def bookTableName = bookClassMetadata.tableName
    
    def authorColumnName = bookClassMetadata.propertyMapping.getColumnNames('author')[0]
    def titleColumnName  = bookClassMetadata.propertyMapping.getColumnNames('title')[0]
    
    def batchSize = 500
    
    def batchSQL = "INSERT INTO ${bookTableName} (${authorColumnName}, ${titleColumnName})" +
                   " VALUES (?,?)"
    
    def sql = new Sql(dataSource)
    
    sql.withBatch(batchSize, batchSQL) { preparedStatement ->
    
        titles.each { title ->
    
                    preparedStatement.addBatch([author, title])
        }
    }