在Slick 3.0中执行批量insertOrUpdate的正确方法是什么?
我正在使用适当的查询的MySQL
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
MySQL bulk INSERT or UPDATE
这是我当前的代码,它非常慢:-(
// FIXME -- this is slow but will stop repeats, an insertOrUpdate
// functions for a list would be much better
val rowsInserted = rows.map {
row => await(run(TableQuery[FooTable].insertOrUpdate(row)))
}.sum
我正在寻找的是相当于
def insertOrUpdate(values: Iterable[U]): DriverAction[MultiInsertResult, NoStream, Effect.Write]
最佳答案
有几种方法可以使此代码更快(每个代码都应该比前面的代码快,但是它的习惯用法越来越少):
insertOrUpdateAll
而不是insertOrUpdate
await(run(TableQuery[FooTable].insertOrUpdateAll rows)).sum
val toBeInserted = rows.map { row => TableQuery[FooTable].insertOrUpdate(row) }
val inOneGo = DBIO.sequence(toBeInserted)
val dbioFuture = run(inOneGo)
// Optionally, you can add a `.transactionally`
// and / or `.withPinnedSession` here to pin all of these upserts
// to the same transaction / connection
// which *may* get you a little more speed:
// val dbioFuture = run(inOneGo.transactionally)
val rowsInserted = await(dbioFuture).sum
val SQL = """INSERT INTO table (a,b,c) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);"""
SimpleDBIO[List[Int]] { session =>
val statement = session.connection.prepareStatement(SQL)
rows.map { row =>
statement.setInt(1, row.a)
statement.setInt(2, row.b)
statement.setInt(3, row.c)
statement.addBatch()
}
statement.executeBatch()
}
关于mysql - Slick 3.0批量插入或更新(upsert),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35001493/