在Slick 2.0中插入后返回AutoInc ID

时间:2014-02-19 22:53:14

标签: scala playframework-2.0 slick play-slick

我已经到了地球的尽头寻找这个问题的答案。光滑的2.0没有太多信息。下面是我的地址模型的代码,如何在创建插入后让方法创建返回id?

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)
        }
      }
    }

谢谢!

2 个答案:

答案 0 :(得分:38)

尝试

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

尚未对其进行测试,但会显示here

答案 1 :(得分:3)

如果您有包含默认值的字段,可以尝试使用

addresses.map(c => (c.city, c.stateName, c.street1)) returning addresses.map(_.id) += (city, stateName, street1)