【问题标题】:What is the best way to deal with compsite keys when using Salat with MongoDB?将 Salt 与 MongoDB 结合使用时,处理复合键的最佳方法是什么?
【发布时间】:2012-01-16 16:11:36
【问题描述】:

我将 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(),这似乎有点笨拙。

【问题讨论】:

  • 如果您创建另一个 val 作为 someRelatedId+email 并使用 @Key("_id") 对其进行注释,如果您不需要它持久化,则将 @Ignore 放在 someRelatedId 上?

标签: scala mongodb salat


【解决方案1】:

这里是 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 更快地看到您的问题。

【讨论】:

  • 绝对有效,但我不喜欢我的域中特定于框架的注释。不过,我确实喜欢将结构保留在复合键中,我想值得更多的深夜黑客攻击。
  • 抱歉,刚看到这个。您可以通过在Context 中添加每个类或全局覆盖来避免注释。这种方法的唯一缺点是,由于对象没有显式注释,任何进行查询的人都需要了解Context 中有覆盖。例如,我认为全球有很多团体将_id 覆盖为id
猜你喜欢
  • 2010-09-07
  • 2013-12-20
  • 2010-09-06
  • 2019-05-26
  • 2016-03-01
  • 2010-10-10
  • 2014-12-13
  • 2018-07-14
  • 1970-01-01
相关资源
最近更新 更多