7

In the following code I can insert my records just fine. But I would really like to get back the ID of the inserted value so that I can then return the object as part of my response.

def postEntry = DBAction { request =>
  request.body.asJson.map {json =>
    json.validate[(String, Long, String)].map {
      case (name, age, lang) => {
        implicit val session = request.dbSession
        val something = Entries += Entry(None, name, age, lang)
        Ok("Hello!!!: " + something)
      }
    }.recoverTotal {
    e => BadRequest("Detected error: " + JsError.toFlatJson(e))
    }
   }.getOrElse {
   BadRequest("Expecting Json data")
  }
}

So I tried changing the insert to:

 val something = (Entries returning Entries.map(_.id)) += Entry(None, name, age, lang)

But I get the following exception:

SlickException: This DBMS allows only a single AutoInc column to be returned from an INSERT

There is a note about it here: http://slick.typesafe.com/doc/2.1.0/queries.html

"Note that many database systems only allow a single column to be returned which must be the table’s auto-incrementing primary key. If you ask for other columns a SlickException is thrown at runtime (unless the database actually supports it)."

But it doesn't say how to just request the ID column.

Eric Goode
  • 156
  • 1
  • 5
  • Doesn't `Entries` have a primary key? I don't think your `id` column is the one, you are passing `None` into `Entry` which makes me think that it's optional. – Ende Neu Aug 29 '14 at 21:35
  • Thanks! You made me think about my mapping and I went back and checked it out. I managed to roll back my primary key def and auto increment def on the Table mapping. – Eric Goode Aug 29 '14 at 22:01

1 Answers1

7

Ende Nue above gave me the hint to find the problem. I needed to have the column marked primary key and auto increment in the table definition.

class Entries(tag: Tag) extends Table[Entry](tag, "entries") {

  def id = column[Option[Long]]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  def age = column[Long]("age")
  def lang = column[String]("lang")

  def * = (id, name, age, lang).shaped <> ((Entry.apply _)tupled, Entry.unapply _)
}

O.PrimaryKey, O.AutoInc

Eric Goode
  • 156
  • 1
  • 5