Simplify inserts into tables with automatic primary keys?

In Slick 1.x, pasting into a table with an automatically generated primary key was quite complicated: you had to manually create a projection of the table that missed pk for insertion purposes. It seems that Slick 2.x will fix this problem:

Soft inserts are now by default, that is, AutoInc columns are automatically skipped when inserting with + =, ++ =, insert, and insertAll. This means that you no longer need separate projections (without a primary key) for inserts.

However, 2.x documents should not be updated:

While some database systems allow you to insert the correct values ​​into AutoInc columns or insert None to get the generated value, most databases prohibit this behavior, so you need not to specify these columns. Slick does not yet have a feature to do this automatically, but it is planned for a future release. For now, you should use a query with a custom projection that does not include an AutoInc column

Does anyone know the new 2.0 syntax for inserting into a table with AutoInc and returning the generated key?

+4
source share
2 answers

, 1.0, , autoinc . , , .insert. ( ), .forceInsert.

+2
  You can retrieve the generated value like this:

  case class Employee( empName: String,empType: String, empId: Int = 0)
        class Employees(tag: Tag) extends Table[Employee](tag, "emp") {
          def empId = column[Int]("id", O.PrimaryKey, O.AutoInc)
          def empName = column[String]("name", O DBType ("VARCHAR(100)"))
          def empType = column[String]("type")
          def * = (empName, empType, empId) <> (Employee.tupled, Employee.unapply)
        }
        val employees = TableQuery[Employees]
        val myInsert = employees.map(e => (e.empName, e.empType)) returning employees.map(_.empId) 
        val autoGenratedKey = myInsert.insert("satendra", "permanent")
+1

All Articles