Is there any way to do multiple inserts/updates in Slick?

眉间皱痕 提交于 2019-12-06 08:35:25

问题


In sql we can do something like this:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

Is there any way to do multiple/bulk/batch inserts or updates in Slick?

Can we do something similar, at least using SQL plain queries ?


回答1:


For inserts, as Andrew answered, you use insertALL.

  def insertAll(items:Seq[MyCaseClass])(implicit session:Session) = {
    (items.size) match {
      case s if s > 0 =>
        try {
          // basequery is the tablequery object
          baseQuery.insertAll(tempItems :_*)
        } catch {
          case e:Exception => e.printStackTrace()
        }
      Some(tempItems(0))
        case _ => None
    }
  }

For updates, you're SOL. Check out Scala slick 2.0 updateAll equivalent to insertALL? for what I ended up doing. To paraphrase, here's the code:

  private def batchUpdateQuery = "update table set value = ? where id = ?"

  /**
   * Dropping to jdbc b/c slick doesnt support this batched update
   */
  def batchUpate(batch:List[MyCaseClass])(implicit session:Session) = {
    val pstmt = session.conn.prepareStatement(batchUpdateQuery)

    batch map { myCaseClass =>
      pstmt.setString(1, myCaseClass.value)
      pstmt.setString(2, myCaseClass.id)
      pstmt.addBatch()
    }

    session.withTransaction {
      pstmt.executeBatch()
    }
  }



回答2:


In Slick, you are able to use the insertAll method for a Table. An example of insertAll is given in the Getting Started page on Slick's website.

http://slick.typesafe.com/doc/0.11.1/gettingstarted.html



来源:https://stackoverflow.com/questions/19226714/is-there-any-way-to-do-multiple-inserts-updates-in-slick

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!