简体   繁体   English

使用Play Framework Anorm,如何获取插入的自动生成的ID?

[英]Using Play Framework Anorm, how do I get the auto-generated id back for an insert?

Suppose I have: 假设我有:

case class SomeModel(
  id : Pk[Long],
  description : String
)

object SomeModel extends Magic[SomeModel] {
  def ayDogAy = {
    var aydog = SomeModel(NotAssigned, "aydog")
    this.insert(aydog)
  }
}

How do I get back the inserted id of aydog? 如何找回插入的aydog ID?

If it matters, my backing database is Postgres 如果重要的话,我的支持数据库是Postgres

在播放2中,如果您具有自动递增的长PK:

val id: Long = SQL("insert into bla bla bla").on("bleh", "blah").executeInsert().get

I don't use the Magic trait (as it is removed in Play 2.0), so I'm not sure if this works here too. 我不使用Magic特性(因为在Play 2.0中已将其删除),所以我不确定这是否也适用。 In SQL you can use SCOPE_IDENTITY() to get the last id used on the connection. 在SQL中,您可以使用SCOPE_IDENTITY()获取该连接上使用的最后一个ID。 So you can do somehing like 所以你可以做一些像

    val id = SQL("SELECT SCOPE_IDENTITY()")().collect {
               case Row(id: Int) => id
             }.head
    new SomeModel(new Id(id), "aydog")

I'm just playing around with Play right now. 我现在正在玩Play。 So this is nothing I'd recommend using in production without further investigations. 因此,我建议您在没有进一步调查的情况下将其用于生产。 I'm especially unsure if there might be concurrency issues, when several threads use the ayDogAy method. 当多个线程使用ayDogAy方法时,我尤其不确定是否可能存在并发问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在PreparedStatement中使用自动生成的@Id? - How to use auto-generated @Id in PreparedStatement? 在PostGres中插入NULL值后,如何自动生成ID? - How do I get my IDs auto-generated when a NULL value is inserted in PostGres? 如何在另一个表的 ID 中的 Postregsql 实体表中插入自动生成的 ID - How to insert an auto-generated id in a Postregsql entity table in another table's ID 如何使用 Anorm 将 JSON 插入 postgres 表? - How do I insert JSON into a postgres table using Anorm? 如何在 Java JPA/Hibernate 中设置不是自动生成的 @Id 主键? - How to set an @Id primary key that is NOT Auto-Generated in Java JPA/Hibernate? ActiveJDBC:save()只能为自动生成的主键生成插入吗? - ActiveJDBC: save() generates insert only for auto-generated primary key? 如何通过Ruby PostgreSQL gem获取自动生成的行主键? - How to get auto-generated row primary key via Ruby PostgreSQL gem? 如何通过自动生成的 PK 使用 Redisson 直写缓存策略 - How can I use Redisson Write-through caching strategy with an auto-generated PK 更改自动生成的序列 - Alter auto-generated sequence Graphql - 如何从自动生成的 graphiql 中省略表格 - Graphql - how to omit tables from the auto-generated graphiql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM