1

I'm curious how I get the inserted object back. I'd like to return the constructed model object in my create API route in Play.

So far I have something like:

def create(username: String, email: String, password:String)(implicit database: Database): Option[FailureResult]  = {
  database withSession {
    implicit session => {
      val affectedRows = users += new User(username=username, email=email, password=password)
      onlyIf(affectedRows != 1){ UnexpectedErrorResult("Unexpected Error: User was not created") }
    }
}

The += operator only returns the affected rows. Is there a way to get the object back without doing another find?

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
Setheron
  • 3,520
  • 3
  • 34
  • 52

1 Answers1

2

You can use the returning method to specify some colums you want to get back from the insert. I've seen it used to get back an auto-incremented id but I guess you could get all columns and reconstruct the object.

I could also point you to my work in progress Slick/Play project where I spent quite a bit of time making these mapping look nice. By the way all of this is Slick 1.0, and lot of stuff as been improved in 2.0 such as the unified semantic of autoinc which makes the code much nicer!

OlivierBlanvillain
  • 7,701
  • 4
  • 32
  • 51