4

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 ?

Vadzim
  • 24,954
  • 11
  • 143
  • 151
Onilton Maciel
  • 3,559
  • 1
  • 25
  • 29

2 Answers2

4

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()
    }
  }
Community
  • 1
  • 1
critium
  • 612
  • 5
  • 16
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

Andrew Jones
  • 1,382
  • 10
  • 26
  • I don't have any information on updates. I searched around and didn't see anything. I want to say that it can't be done based on my research coming up with nothing, but I don't want to provide misinformation. – Andrew Jones Oct 07 '13 at 21:12