2016-07-01 39 views
1

當添加一本書,你可以這樣做:的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'] 

如何通過一次調用數據庫來保存所有書籍?

+0

不要使用'沖水:TRUE'讓Grails的給他們一次全部 – doelleri

回答

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