Anorm和enum字段

时间:2012-01-23 15:19:44

标签: scala enums playframework anorm

我只是想知道如何使用Anorm在我的case类中使用枚举文件(类,从Enumeration扩展)。例如:

object Type extends Enumeration {
    type Type = Value
    val User, Admin = Value
}

case class User (
    id: Pk[Long],
    type: Type.Type
)

如果我尝试这样的代码,我会得到“RuntimeException:没有类型models.User支持的构造函数”。我应该为此目的使用什么DB字段类型?我没有运气就尝试过varchar。

1 个答案:

答案 0 :(得分:1)

你可以用反射来做。给定下面的代码(scala 2.10),执行类似

的导入
import AnormEnumerationExtension.ToId._

并且你的枚举通过它的id持续存在。如果你想坚持使用它的名字

import AnormEnumerationExtension.ToName._

最后是EnumExtension:

import java.lang.reflect.InvocationTargetException
import scala.reflect.runtime.universe._

object AnormEnumerationExtension {      
  private lazy val rm = scala.reflect.runtime.currentMirror

  object ToId {
    implicit def enumToParameterValue[E <: Enumeration: TypeTag](enumValue: E#Value): ParameterValue[Int] = enumValue.id

    implicit def rowToEnumValue[E <: Enumeration: TypeTag]: Column[E#Value] = Column.nonNull { (value, meta) =>
      val MetaDataItem(qualified, _, _) = meta
      value match {
        case int: Int => {
          val methodSym = typeTag[E].tpe.member(newTermName("apply")).asMethod
          val im = rm.reflect(rm.reflectModule(typeOf[E].termSymbol.asModule).instance)
          try {
            Right(im.reflectMethod(methodSym)(int).asInstanceOf[E#Value])
          } catch {
            case e: InvocationTargetException if e.getCause.isInstanceOf[NoSuchElementException] =>
              Left(SqlMappingError(s"Can't convert $int to ${typeTag[E].tpe}, because it isn't a valid value: $qualified"))
          }
        }
        case _ => Left(TypeDoesNotMatch(s"Can't convert [$value:${value.asInstanceOf[AnyRef].getClass}] to ${typeTag[E].tpe}: $qualified"))
      }
    }
  }

  object ToName {
    implicit def enumToParameterValue[E <: Enumeration: TypeTag](enumValue: E#Value): ParameterValue[String] = enumValue.toString

    implicit def rowToEnumValue[E <: Enumeration: TypeTag]: Column[E#Value] = Column.nonNull { (value, meta) =>
      val MetaDataItem(qualified, _, _) = meta
      value match {
        case string: String => {
          val methodSym = typeTag[E].tpe.member(newTermName("withName")).asMethod
          val im = rm.reflect(rm.reflectModule(typeOf[E].termSymbol.asModule).instance)
          try {
            Right(im.reflectMethod(methodSym)(string).asInstanceOf[E#Value])
          }
          catch {
            case e: InvocationTargetException if e.getCause.isInstanceOf[NoSuchElementException] =>
              Left(SqlMappingError(s"Can't convert '$string' to ${typeTag[E].tpe}, because it isn't a valid value: $qualified"))
          }
        }
        case _ => Left(TypeDoesNotMatch(s"Can't convert [$value:${value.asInstanceOf[AnyRef].getClass}] to ${typeTag[E].tpe}: $qualified"))
      }
    }
  }
}