ScalikeJdbc 多重插入

ScalikeJdbc Multiple Insert

我们如何在同一事务中执行多个插入?

  def insertData(dataList: List[Data])(implicit session: DBSession = autoSession) = {

    // todo: this is probably opening and closing a connection every time?
    dataList.foreach(data => insertData(data))
  }

  def insertData(data: Data) = withSQL {
    val t = DataTable.column
    insert.into(DataTable).namedValues(
      d.name -> data.name,
      d.title -> data.title
    )
  }.update().apply()

如果这些插入的数量达到数千或更多,则为每个插入设置不同的事务将不会有效。

http://scalikejdbc.org/documentation/operations.html

像这样修改您的 insertData 方法:

def insertData(data: Data)(implicit session: DBSession = AutoSession) = withSQL {
  val t = DataTable.column
  insert.into(DataTable).namedValues(
    d.name -> data.name,
    d.title -> data.title
  )
}.update().apply()

然后,使用DB.localTx:

DB.localTx { implicit s =>
  dataList.foreach(data => insertData(data))
}