Grails 3.1 - 多个插入域

时间:2016-07-01 19:10:02

标签: grails gorm grails-3.1

添加单本图书时,您可以这样做:

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

说我想一次添加一些书籍,例如输入是:

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

如何通过一次调用数据库来保存所有图书?

2 个答案:

答案 0 :(得分:0)

此博文可能有所帮助:http://www.tothenew.com/blog/batch-processing-in-grails/。基本上,没有批量保存,您需要注意会话的大小增加太多。博客作者最终的最终代码如下:

List  batch = []
(0..50000).each {
    Person person = new Person(....)
    batch.add(person)
    if (batch.size() > 1000) {
        Person.withTransaction {
            for (Person p in batch) {
                p.save()
            }
        }
        batch.clear()
    }
    session = sessionFactory.getCurrentSession()
    session.clear()             
}

答案 1 :(得分:-1)

Groovy SQL解决方案:

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])
    }
}