简体   繁体   English

Slick中的Scala Enumerations(案例对象),良好实践

[英]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]? 存储Ints并使用隐式函数MappedColumnType.base [Int,DoorState]将它们映射到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. MySQL ENUM就像映射到String一样。 See http://slick.typesafe.com/doc/2.1.0/userdefined.html#using-custom-scalar-types-in-queries 请参阅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 然后,您可以将DoorState用作列类型,如下所示

column[DoorState] or Column[DoorState] column[DoorState]Column[DoorState]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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