【问题标题】:How to set a column default value to Null? (in slick)如何将列默认值设置为 Null? (光滑)
【发布时间】:2016-09-14 22:56:32
【问题描述】:
case class Account(var email:String, var pass:String, var familyId: Int, var accessId: Int, id: Option[Int] = None)

// A Accounts table with 5 columns: id, email, pass, familyId, accessId
class Accounts(tag: Tag) extends Table[Account](tag, "ACCOUNTS") {

  def id = column[Int]("ID", O.AutoInc, O.PrimaryKey)
  def email = column[String]("EMAIL")
  def pass = column[String]("PASS")
  def familyId = column[Int]("FAMILY_ID")                            // TODO: add fk family_id
  def accessId = column[Int]("ACCESS_ID")                            // TODO: add fk access_id

  def * = (email, pass, familyId, accessId, id.?) <> (Account.tupled, Account.unapply)

}

用这种结构创建表后,表中的所有列都是Not Null

那么如何将它们设置为Nullable,并将它们的值设置为Null

【问题讨论】:

  • 我想你可能只想use the slick code generator 来生成这些东西......(这并不能回答问题,我知道......它希望这个问题没有实际意义!)。该问题的实际答案涉及将列声明为值的选项,但由于我们生成了这些东西,我不需要了解细节:)

标签: scala slick slick-3.0


【解决方案1】:

我们可以通过在case class 中将nullable 字段声明为Option[T] 来做到这一点

假设我们有User 类,我们希望age 的值是nullable,并且年龄的默认值是null。所以我们像下面这样声明我们的类。注意年龄是Option[Int]

case class User(name: String, age: Option[Int])

class Users(tag: Tag) extends Table[User](tag, "users") {
  def name = column[String]("name")
  def age = column[Option[Int]]("age", O.Default(None)) //notice default value is None which translates to Null in database
  def * = (name, age) <> (User.tupled, User.unapply)
}

age 字段可以为 null,其默认值为 null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2019-08-17
    • 2016-04-11
    • 1970-01-01
    相关资源
    最近更新 更多