2

I'm currently developping a small application in Scala using the Play framework and I would like to persist a list of operations made by a user. Is is possible to store a simple list of ids (List[Long]) using just Anorm like I'm doing?

Otherwise, what else could I use to make it work? Do I need to use an ORM like explained in Scala Play! Using anorm or ORM?

Community
  • 1
  • 1

3 Answers3

2

If you're talking about persisting to a SQL database then Anorm can certainly handle that for you.

At the most basic level, you could create a table of long integers in your SQL database and then use Anorm to persist your list. Assume your store your integers in a single-column table called UserActions with its sole column called action:

def saveList(list: List[Long]) = {
  DB.withConnection { implicit connection =>
    val insertQuery = SQL("insert into UserActions(action) values ({action})")
    val batchInsert = (insertQuery.asBatch /: list)(
      (sql, elem) => sql.addBatchParams(elem)
    )
    batchInsert.execute()
  }
}

I threw together a little demo for you and I'm pushing it to Heroku, I'll update with the link soon (edit: Heroku and I aren't getting along tonight, sorry).

The code is in my Github at: https://github.com/ryantanner/anorm-batch-demo

Look in models/UserActions.scala to find that snippet specifically. The rest is just fluff to make the demo more interesting.

Now, I'd take a step back for a moment and ask yourself what information you need about these user operations. Semantically, what does that List[Long] mean? Do you need to store more information about those user actions? Should it actually be something like rows of (UserID, PageVisited, Timestamp)?

Ryan
  • 7,227
  • 5
  • 29
  • 40
  • I will explain a little bit more. I have an object User (with a table user to persist it) and I would like to represent an object Order which would represent an order made by a User. An Order may be composed of one or more Item (-> list?) and a User may have pore than one Order (-> list?). Now, to persist this, I planned to store a list of order ids (List[Long]) in the table user and a list of item ids (List[Long]) in the table order. Unless you have a better idea... – user1194311 Mar 20 '13 at 21:50
0

Untested

I think you need to create a batch insert statement like this:

  val insertStatement = 
    SQL("""INSERT INTO UserOperations (id) VALUES ({id})""")
   .asBatch
   .addBatchParamsList(List(Seq(1),  Seq(2)))
   .execute()
EECOLOR
  • 11,184
  • 3
  • 41
  • 75
0

BatchSql of Anorm have been recently updated. You may want to check out the latest.

cchantep
  • 9,118
  • 3
  • 30
  • 41