且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用slick/plainSQL检索自动递增的ID?

更新时间:2023-09-23 23:25:34

感谢您 cvogt 在此讨论中提供了帮助. 我认为提交PR会有所帮助,因为它是非常常见且有用的功能,在

Thank you cvogt for helping out in this discussion. I think it would be helpful to submit a PR, inasmuch as it is a very common and useful functionality which should not be missing in slick's plainSQL queries.

最后,我找到了一种解决方法来替换缺少的本机函数,如下所示.

Finally, i found a work-around to replace the missing native function as following.

在同一会话中,我解决了两个查询.第一个是INSERT语句,第二个语句是SELECT LAST_INSERT_ID(),它返回由最近执行的INSERT(1)为AUTO_INCREMENT列设置的最新自动生成的值.此处有更多详细信息: MySQL参考-LAST_INSERT_ID()

Within the same session I settle two queries. The first one is the INSERT statement, the second statement is SELECT LAST_INSERT_ID() which returns the newest automatically generated value that was set for the AUTO_INCREMENT column by the recently executed INSERT(1). More details here: MySQL Reference - LAST_INSERT_ID()

Database.forDataSource(dataSource).withDynSession {
  sqlu"""INSERT INTO `users`(`email`) VALUES ("theEmailAdress@test.de")
  """.firstOption match {
    case Some(num) if num == 1 => sql"SELECT LAST_INSERT_ID()".as[Long].firstOption()
    case None => None
  }
}

这现在对我有效.如果有任何改进,请随时发布您的解决方案.

This works for me right now. If there are any improvements, do not hesitate to post your solution.