Question

I have the following sql query to a db in a Play 2.2 app:

SQL("SELECT t.id, t.field1, t.field2 from table1 t WHERE t.field1 = {param1}")
   .on("param1" -> param1)()
   .map {
       case ???
    }.toList

This request can return:

  1. no records
  2. record(s) but field2 is NULL
  3. record(s) where field2 is NOT NULL

How do I handle these cases? I only know how to handle a single column:

//...
.map {
  case Row(field1: Option[String]) => field1
 }.toList
Was it helpful?

Solution

Use a row parser, documented here:

http://www.playframework.com/documentation/2.2.x/ScalaAnorm

For example:

val results: List[(Int, Int, String)] = 
  SQL("SELECT t.id, t.field1, t.field2 from table1 t WHERE t.field1 = {param1}")
    .on("param1" -> param1)()
    .as(int("t.id") ~ int("t.field1") ~ get[Option[String]]("t.field2") map(flatten) *)
    .toList 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top