Using Lift Record, when I try to retrieve the MongoDB entry below, a NullPointerException
is raised when the .asHtml
method of MongoCaseClassField
is called.
object MyEnumeration extends Enumeration {
val A, B, C = Value
}
case class MyCaseClass(en: MyEnumeration.Value)
class MyRecord extends MongoRecord[MyRecord] with MongoId[MyRecord] {
def meta = MyRecord
object fail extends MongoCaseClassField[MyRecord, MyCaseClass](this)
}
object MyRecord extends MyRecord with MongoMetaRecord[MyRecord]
However this wor开发者_开发问答ks fine if I use String
instead of Enumeration
. Is there any way to use enumerations in case class fields or should use a different type of field?
At the time of writing mongoDB doesn't place nice with scala enums, I use a decorator method as a work around.
Say you have this enum:
object EmployeeType extends Enumeration {
type EmployeeType = Value
val Manager, Worker = Value
}
and this mongodb record:
import EmployeeType._
case class Employee(
id: ObjectId = new ObjectId
)
In your mongoDB, store the integer index of the enum instead of the enum itself:
case class Employee(
id: ObjectId = new ObjectId,
employeeTypeIndex: Integer = 0
){
def employeeType = EmployeeType(employeeTypeIndex); /* getter */
def employeeType_=(v : EmployeeType ) = { employeeTypeIndex= v.id} /* setter */
}
The extra methods implement getters and setters for the employee type enum.
I am quite certain that this will only work with native types like String, Int, Float, Double, Boolean, etc, but not Enumerations. I am really certain that this is due to serialization.
精彩评论