Using Auto Incrementing fields with PostgreSQL and Slick

前端 未结 7 1995
無奈伤痛
無奈伤痛 2020-12-30 00:43

How does one insert records into PostgreSQL using AutoInc keys with Slick mapped tables? If I use and Option for the id in my case class and set it to None, then PostgreSQL

7条回答
  •  清酒与你
    2020-12-30 01:34

    The simplest solution was to use the SERIAL type like this:

    def id = column[Long]("id", SqlType("SERIAL"), O.PrimaryKey, O.AutoInc)

    Here's a more concrete block:

    // A case class to be used as table map
    case class CaseTable( id: Long = 0L, dataType: String, strBlob: String)
    
    // Class for our Table
    class MyTable(tag: Tag) extends Table[CaseTable](tag, "mytable") {
      // Define the columns
      def dataType = column[String]("datatype")
      def strBlob = column[String]("strblob")
    
      // Auto Increment the id primary key column
      def id = column[Long]("id", SqlType("SERIAL"),  O.PrimaryKey,  O.AutoInc)
    
      // the * projection (e.g. select * ...) auto-transforms the tupled column values
      def * = (id, dataType, strBlob) <> (CaseTable.tupled, CaseTable.unapply _)
    
    }
    
    
    // Insert and  get auto incremented primary key
    def insertData(dataType: String, strBlob: String, id: Long = 0L): Long = {
      // DB Connection
      val db = Database.forURL(jdbcUrl, pgUser, pgPassword, driver = driverClass)
      // Variable to run queries on our table
      val myTable = TableQuery[MyTable]
    
      val insert = try {
        // Form the query
        val query = myTable returning myTable.map(_.id) += CaseTable(id, dataType, strBlob)
        // Execute it and wait for result
        val autoId = Await.result(db.run(query), maxWaitMins)
        // Return ID
        autoId
      }
      catch {
        case e: Exception => {
          logger.error("Error in inserting using Slick: ", e.getMessage)
          e.printStackTrace()
          -1L
        }
      }
      insert
    }
    

提交回复
热议问题