Grails 3.1 - 多次插入域
Grails 3.1 - Multiple inserts into domain
添加单本书时,您可以这样做:
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']
如何一次调用数据库保存所有书籍?
此博客 post 可能对您有所帮助: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()
}
A 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])
}
}
添加单本书时,您可以这样做:
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']
如何一次调用数据库保存所有书籍?
此博客 post 可能对您有所帮助: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()
}
A 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])
}
}