Storing case object with squeryl

徘徊边缘 提交于 2019-12-10 22:06:29

问题


How do I store user case objects with squeryl? I have an Account object with a permission field of type Permission (defined as a sealed trait). I also have 2 case objects (Administrator and NormalUser) extending from Permission. How can I persist the Account class using Squeryl. Example code below:

sealed trait Permission
case object Administrator extends Permission
case object NormalUser extends Permission

case class Account(
        id: Long, 
        email: String,
        permission: Permission
) extends KeyedEntity[Long]

回答1:


Expanding on my comment, if you use a custom type to retrieve the permission type, such that it persists to the database as an integer (in the example below 1 and 0), you can override the unapply method to lookup the case object and pattern matching should work fine. I imagine something like the following should work:

class Permission(identifier:Int) extends org.squeryl.customtypes.IntField(identifier) {
  self: CustomType[Int] =>

  private lazy val permissions = 
    List(Administrator, NormalUser).
      map(p => p.value -> p).
      toMap

  def unapply = permissions.get(value)
}

case object Administrator extends Permission(1)
case object NormalUser extends Permission(0)

Then you should be able to store the permission directly in your code, using your entity definition:

case class Account(
        id: Long, 
        email: String,
        permission: Permission
) extends KeyedEntity[Long]

you can set the permission field directly as Administrator or NormalUser and you should also be able to pattern match like:

account.permission match {
  case Administrator => ..
  case NormalUser => ..
}



回答2:


You need to define schema:

 object Library extends Schema {

     val authors = table[Author]("AUTHORS")
 }

and then insert entity:

 authors.insert(new Author("Herby Hancock"))

http://squeryl.org/schema-definition.html

http://squeryl.org/inserts-updates-delete.html

In order to store Permission it must inherit one of the subtypes of CustomType in the package org.squeryl.customtypes, and import the org.squeryl.customtypes.CustomTypesMode._ into the scope where statements are defined. For details read section Custom Types here: http://squeryl.org/schema-definition.html



来源:https://stackoverflow.com/questions/13219104/storing-case-object-with-squeryl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!