gpt4 book ai didi

grails - Grails 3.1-多个插入域

转载 作者:行者123 更新时间:2023-12-02 14:56:03 25 4
gpt4 key购买 nike

当添加一本书时,您可以执行以下操作:

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']

如何通过一次调用保存所有书籍?

最佳答案

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

关于grails - Grails 3.1-多个插入域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38152498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com