Slick中的Scala枚举(案例对象),良好实践 [英] Scala Enumerations (case objects) in Slick, good practice
问题描述
假设我有一个代表一组几个有效状态的特征。将对象存储在数据库中是一种好习惯吗?使用隐式函数MappedColumnType.base [Int,DoorState]存储Ints并将其映射到DoorState会更好吗?
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")
...
}
推荐答案
制造商的建议使用:
implicit def doorStateMapper = MappedColumnType.base[DoorState, Int]( ... )
您的案例对象和整数(我假设这是您的数据库列的类型)。需要在表和查询的范围内。您还可以映射到字符串或任何其他内容。 MySQL ENUM就像映射到String一样。请参见 http:// slick。 typesafe.com/doc/2.1.0/userdefined.html#using-custom-scalar-types-in-queries
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使您可以使用DoorState作为列类型,如
THIS then enables you to use DoorState as a Column type as in
column [DoorState]
或 Column [DoorState]
这篇关于Slick中的Scala枚举(案例对象),良好实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!