首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Anorm中保存新对象时检索主键

如何在Anorm中保存新对象时检索主键
EN

Stack Overflow用户
提问于 2012-03-25 19:12:20
回答 1查看 4.5K关注 0票数 18

我正在使用Scala Play!使用Anorm框架将数据模型持久化到数据库。我遵循了示例代码here

case class Bar(id: Pk[Long], name: String)

object Bar {

  val simple = {
    get[Pk[Long]]("id") ~
    get[String]("name") map {
      case id~name => Bar(id, name)
    }
  }

  def findAll(): Seq[Bar] = {
    DB.withConnection { implicit connection =>
      SQL("select * from bar").as(Bar.simple *)
    }
  }

  def create(bar: Bar): Unit = {
    DB.withConnection { implicit connection =>
      SQL("insert into bar(name) values ({name})").on(
        'name -> bar.name
      ).executeUpdate()
    }
  }

}

尝试对其进行扩展,我希望检索刚刚创建的主键并将其存储在case类中。

如何检索主键?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-25 19:17:27

使用executeInsert方法而不是executeUpdate方法。注意到here,foremer方法返回Option[T],其中T是主键的类型。

您可以使用match语句提取该值:

    DB.withConnection { implicit connection =>
        SQL(...).executeInsert()
    } match {
        case Some(long) => long // The Primary Key
        case None       => ...
    }
票数 35
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9859700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档