Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning AutoInc ID after Insert in Slick 2.0

Tags:

I have looked to the ends of the earth for the answer to this question. There is not much info out there on slick 2.0. Below is my code for my Addresses model, how would I have the method create return the id after it made the insert?

package models
import play.api.Play.current
import play.api.db.slick.Config.driver.simple._
import play.api.db.slick.DB

    object Addresses{
      val DB_URL:String = "jdbc:h2:mem:fls-play"
      val DB_driver:String = "org.h2.Driver"
      class Addresses(tag: Tag) extends Table[(String, String, String, String, String)](tag, "ADDRESSES"){
       def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
       def city = column[String]("CITY")
       def stateName = column[String]("STATE_NAME")
       def street1 = column[String]("STREET1")
       def street2 = column[String]("STREET2")
       def zip = column[String]("ZIP")

       def * = (city, stateName, street1, street2, zip)
      }
      val addresses = TableQuery[Addresses]

      def create(city:String, stateName:String, street1:String, street2:String, zip:String) {
        DB.withSession{ implicit session =>
           addresses += (city, stateName, street1, street2, zip)
        }
      }
    }

Thank you!

like image 948
James Little Avatar asked Feb 19 '14 22:02

James Little


2 Answers

Try

(addresses returning addresses.map(_.id)) += (city, stateName, street1, street2, zip)

haven't tested it, but it is shown here

like image 107
Martin Kolinek Avatar answered Oct 04 '22 02:10

Martin Kolinek


If you have fields with default values you may try this

addresses.map(c => (c.city, c.stateName, c.street1)) returning addresses.map(_.id) += (city, stateName, street1)
like image 40
andemi Avatar answered Oct 04 '22 00:10

andemi