使用平滑插入后返回自动递增值 [英] Returning the auto incrementing value after an insert using slick

查看:72
本文介绍了使用平滑插入后返回自动递增值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用slick 2.0.1(并且可以根据需要进行升级),并且我想从数据库(PostgreSQL)中检索自动递增值.

I am using slick 2.0.1 (and can upgrade if required) and I want to retrieve the auto incrementing value from the database (postgresql).

我已经在SO上看到了一些问题,但是它们已经很老了,我希望有一种更好的方法,比做这个答案所建议的要好:

I have seen a few questions on SO on this already, but they are fairly old and I was hoping there was a better way than to do what this answer suggests: Scala & Play! & Slick & PostgreSQL auto increment

def autoInc = name ~ price ~ description returning id

def add(product: Product)(implicit s:Session): Long = {
    Products.autoInc.insert(p.name, p.price, p.description)
}

您必须在autoInc方法中重新输入模型的字段,该方法重复了我希望避免的事情.

有没有更好的方法,或者我应该这样做吗?

我选择的方式是让我的模型保持姿势(像普通的Scala对象一样):

The way I have chosen is to have my models poso (plain old scala objects like):

case class Product(.....)

然后我的dao类如下:

And then my dao class looks like:

class ProductDao extends ProductDao {
  class Products(tag: Tag) extends Table[Product](tag, "products") {

     def id = ...
     def name = ..

     def * = (id, name) <> (Product.tupled, Product.unapply)

  }

  val products = TableQuery()
}

另外,对于*方法,我是否必须输入所有类似的属性,或者还有更好的方法吗?

Also as a side note, for the * method do I have to enter all the properties like that or is there a better way for that also?

推荐答案

您看到的autoIncforInsert投影模式适用于Slick 1而非Slick 2,其中自动递增的值在插入中被自动忽略.请参见 http://slick.typesafe.com/doc/2.0.2/migration.html#inserting

The autoInc or forInsert projection pattern you have seen applies to Slick 1 but not Slick 2, where auto incremented values are automatically ignored in inserts. See http://slick.typesafe.com/doc/2.0.2/migration.html#inserting

您能比重复列名更好吗?还是您的数据模型的工件有多种表现形式?代码生成是一种实现方法: http://slick.typesafe. com/doc/2.0.2/code-generation.html 我将在Scala大会上谈到这一点.

Can you better than repeating your column names? Or multiple manifestations of artifacts of your data model for that matter? Code generation is one way to do it: http://slick.typesafe.com/doc/2.0.2/code-generation.html I will be speaking about this at Scala days.

要返回ID,请像在Slick 1中一样使用returning. http://slick.typesafe.com/doc/2.0.2/queries.html#inserting

For returning the id use returning just like in Slick 1. http://slick.typesafe.com/doc/2.0.2/queries.html#inserting

这篇关于使用平滑插入后返回自动递增值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆