简体   繁体   中英

Get most recently inserted primary key slick

Does anyone know how to get the most recently inserted id of an auto incremented column in Slick? I want to perform an insertion of entry using Slick, then get back the value of the primary column id that was most recently inserted using Scala/Slick, and then use it for another insertion.

You can use returning :

val someTable = TableQuery[MyEntity]
val thisId = (someTable returning someTable.map(_.id)) += someRow

Note that this returns the id of the inserted row (which could or could not be the most recent), so only after the row is stored inserted in the database.

The problem with this is that you shouldn't use it for another insertion, the reason why you have an auto incremented column is that you want the DB layer to handle that column for you and dynamically assign an identifier, think about what could happen in your case, you insert a row and get back an id, let's say 10, then you want to insert a row with id 11 but you don't know if some other part of your application is currently in a session and inserting a row, if it does and succeed you will try to insert a row with duplicate id and get back an exception.

Also ids could be not sequential, meaning that you could have holes in the column if some rows is deleted, in that case the auto increment won't fill those holes, but just keep incrementing the id value from the last id.

If you want to select it from the information schema you can use plain SQL (I am afraid slick allows this queries on information schema):

SELECT 
  Auto_increment 
FROM 
  information_schema.tables 
WHERE 
  table_name='the_table_you_want';

Taken from this post, note from the comments that in general it's not guaranteed that the returned id is not already used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM