简体   繁体   中英

Scala Enumerations (case objects) in Slick, good practice

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")
  ...
}

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM