scala - 将 Salat 与 MongoDB 一起使用时,处理复合键的最佳方法是什么?

标签 scala mongodb salat

我将 Salat 与 MongoDB 一起使用,并且我正在尝试转换为自然键以避免数据库中的重复。我使用的案例类看起来有点像:

case class Foo(someRelatedId: String, email: String ...)

我想添加一个由 someRelatedId+email 组成的自然键,并让 MongoDB 使用它而不是默认的 ObjectId。从文档中我觉得这是可能的,但我仍在摸索一个可行的解决方案。这在很大程度上是由于我对 Scala 本身缺乏熟练程度,我敢肯定。

更新:我现在有一个可行的解决方案,但我仍然想知道这是否是最好的方法

case class Foo(someRelatedId: String, email: String, naturalKey: String)

object Foo {
  def apply((someRelatedId: String, email: String) {
    apply(someRelatedId, email, someRelatedId+email)
  }
}

然后在 package.scala 中映射到 custom salat context :

implicit val ctx = new Context() {
  val name = Some("Custom Context")
}
ctx.registerGlobalKeyOverride(remapThis = "naturalKey", toThisInstead = "_id")

这样我可以避免在我的域类中使用强制性(无意义的)_id 字段,但我必须在伴随对象上重载 apply(),这似乎有点笨拙。

最佳答案

这里是 Salat 的主要开发者。

像 Milan 建议的那样,为您的复合键创建一个案例类:

case class FooKey(someRelatedId: String, email: String)

case class Foo(@Key("_id") naturalKey: FooKey) {

  // use @Persist if you want these fields serialized verbatim to Mongo - see https://github.com/novus/salat/wiki/Annotations for details
  @Persist val email =  naturalKey.email
  @Persist val someRelatedId = naturalKey.someRelatedId

}

object FooDAO extends SalatDAO[Foo, FooKey](collection = /*  some Mongo coll */ )

如果您反对将“_id”作为字段名称,您可以在上下文中使用全局覆盖将“_id”重新映射到“naturalKey”,或者在每个对象上提供临时 @Key 覆盖。

我个人不喜欢在你的模型中给 _id 一个不同的名字,因为你的 Mongo 查询必须使用序列化键“_id”,而你的所有业务逻辑都必须使用案例类字段名称(“naturalKey”或其他) ,但 YMMV。

附:我们的邮件列表位于 http://groups.google.com/group/scala-salat - 我会比 Stack Overflow 更快地看到你的问题。

关于scala - 将 Salat 与 MongoDB 一起使用时,处理复合键的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8882797/

相关文章:

mongodb - 计算对象属性在 mongo 对象数组中存在的次数

scala - 如何查询 Array[String] 中的正则表达式匹配项?

mongodb - 使用子类检索 Salat 对象时出现异常

mysql - 设置过程中出现异常

scala - 为什么 scala.util.Success.apply 不是无限递归的?

javascript - Mongoose 如何发送交易多个集合

mongodb - 无法使用 salat : command failed [listDatabases] 从 Play 应用程序连接到 MongoDB

scala - Scala 中具有 F 界类型和存在类型的编译问题

scala - 如何将这三个类轮写成一个类轮?

node.js - Mongo 嵌套数组有条件更新