What is the best way to get the last inserted auto-generated id using a spot?

I am using Slick (Scala) for my project. My problem is how to recover the last inserted identifier using the raised deployment API. The identifier automatically increases. I read the documentation, but I'm afraid I did not understand it well enough. Can you provide a more detailed explanation and sample code on how to do this?

+4
source share
1 answer

As described in the Slick documentation , you can use the returning <Table>.id .

Suppose you have a cat defined in a slippery manner:

 case class Cat(id: Option[Int], name: String) object Cats extends Table[Cat]("cats") { def id = column[Int]("cat_id", O.PrimaryKey, O.AutoInc) def name = column[String]("name") def * = id.? ~ name <> (Cat.apply _, Cat.unapply _) } 

Then you can get the newly created id the moment you insert a new cat.

 val newCatId = Cats returning Cats.id insert Cat(None, "Cringer") 

Hope that helps;)

+4
source

Source: https://habr.com/ru/post/1501275/


All Articles