用squeryl存储案例对象 [英] Storing case object with squeryl
问题描述
如何使用squeryl存储用户案例对象?我有一个Account对象,其权限字段为Permission(定义为密封特征)类型.我还从Permission扩展了2个案例对象(Administrator和NormalUser).如何使用Squeryl保留Account类.下面的示例代码:
How do I store user case objects with squeryl? I have an Account object with a permission field of type Permission (defined as a sealed trait). I also have 2 case objects (Administrator and NormalUser) extending from Permission. How can I persist the Account class using Squeryl. Example code below:
sealed trait Permission
case object Administrator extends Permission
case object NormalUser extends Permission
case class Account(
id: Long,
email: String,
permission: Permission
) extends KeyedEntity[Long]
推荐答案
请扩展我的评论,如果您使用自定义类型来检索权限类型,则该权限类型将作为整数持久化到数据库中(在下面的示例中为1)和0),您可以覆盖unapply方法来查找case对象,并且模式匹配应该可以正常工作.我认为类似以下内容的方法应该起作用:
Expanding on my comment, if you use a custom type to retrieve the permission type, such that it persists to the database as an integer (in the example below 1 and 0), you can override the unapply method to lookup the case object and pattern matching should work fine. I imagine something like the following should work:
class Permission(identifier:Int) extends org.squeryl.customtypes.IntField(identifier) {
self: CustomType[Int] =>
private lazy val permissions =
List(Administrator, NormalUser).
map(p => p.value -> p).
toMap
def unapply = permissions.get(value)
}
case object Administrator extends Permission(1)
case object NormalUser extends Permission(0)
然后,您应该能够使用您的实体定义将权限直接存储在代码中:
Then you should be able to store the permission directly in your code, using your entity definition:
case class Account(
id: Long,
email: String,
permission: Permission
) extends KeyedEntity[Long]
您可以直接将permission
字段设置为Administrator
或NormalUser
,并且还应该能够像这样进行图案匹配:
you can set the permission
field directly as Administrator
or NormalUser
and you should also be able to pattern match like:
account.permission match {
case Administrator => ..
case NormalUser => ..
}
这篇关于用squeryl存储案例对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!