问题
Suppose I have a trait representing a set of several valid states. Would it be a good practice to store the objects in the database? Would it be better to store Ints and map them to DoorState with an implicit function MappedColumnType.base[Int, DoorState]?
trait DoorState
case object Open extends DoorState
case object Closed extends DoorState
class Doors(tag: Tag) extends Table[Door](tag, "DOORS") {
...
def state = column[DoorState]("DOOR_STATE")
...
}
回答1:
Recommendation from the makers use:
implicit def doorStateMapper = MappedColumnType.base[DoorState, Int]( ... )
to map between your case objects and ints (which I am assuming is the type of your database column). Needs to be in scope for tables and queries. You can also map to strings or whatever. MySQL ENUM are just like mapping to String. See http://slick.typesafe.com/doc/2.1.0/userdefined.html#using-custom-scalar-types-in-queries
THIS then enables you to use DoorState as a Column type as in
column[DoorState]
or Column[DoorState]
来源:https://stackoverflow.com/questions/28331528/scala-enumerations-case-objects-in-slick-good-practice