I’m using Play Framework 2.0 for a few of my projects and I find it amazing. Lately I had a little problem with the
executeInsert() method of Anorm. This method, executes the query and returns an
Option[Long] which is the id of the inserted row. That’s all fine when you do single row inserts but what happens when you do multiple row insert?
Well .. I was getting this error:
Execution exception[[RuntimeException: SqlMappingError(too many rows when expecting a single one)]]
This was a bit of a problem because the alternative methods (
executeUpdate()) provided by the framework also didn’t return what I wanted (the ids of the new rows).
So what should I do? I decided to dive into the code of Anorm and see what’s going on. I opened the Anorm.scala on GitHub and found the code of
executeInsert (link to that line of code). Immediately after I read the implementation I realised that the method was taking an implicit parameter, which happened to be the result parser that collects the inserted row ids. And that parser was by default set to
So the solution to my problem was very simple! I just had to provide another parser as a parameter that would return me all the rows. Can you guess what would that be?
.executeInsert( scalar[Long] * )
Hope this blog post will be useful to somebody else in the future 🙂 .. that’s why I’m writing it anyway!
Have a nice day!!