Scala Enumerations (case objects) in Slick, good practice

旧街凉风 提交于 2020-01-03 17:29:02

问题


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

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