与 lift Mapper 的一对一关系

发布于 2024-10-01 02:45:15 字数 157 浏览 0 评论 0原文

如何与 Mapper 实现一对一关系? 来自电梯维基:

如果您想要建立一对一关系的模型,只需使用一对多关系即可。唯一潜在的麻烦是您将拥有一个 List[B] 而不是 Box[B]。

难道就没有更惯用的方法吗?

How do I implement a One-to-One relationship with Mapper?
From Lift wiki:

If you’re looking to model a one-to-one relationship, just use a one-to-many relationship. The only potential hassle is that you’ll have a List[B] instead of a Box[B].

Isn't there a more idiomatic way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

っ〆星空下的拥抱 2024-10-08 02:45:15

我可能会通过降低一对多关系的可见性并创建一个 getter/setter 来实现它:

protected object comments extends 
  MappedOneToMany(Comment, Comment.post, OrderBy(Comment.id, Ascending))

def comment : Option[Comment] = {
  comments match {
    case Nil => None
    case head :: _ => Some(head)
  }
}

def comment_=(comment: Comment) = {
  comments.clear
  comments += comment
}

理想吗?不。但是比让客户端代码处理 List[Comment] 而不是 Option[Comment] 更惯用吗?我想是的。

沿着同样的思路,您还可以创建自己的类来扩展 MappedOneToMany。这段代码未经测试,但我相信它的精神:

class MappedOneToOne[K,T<:KeyedMapper[K, T],O <: Mapper[O]]
  (meta: MetaMapper[O], foreign: MappedForeignKey[K,O,T], qp: QueryParam[O]*) extends MappedOneToMany(meta, foreign, qp) {

  def get : Option[O] = {
    all match {
      case Nil => None
      case head :: _ => Some(head)
    }
  }

  def set(o: O) : O = {
    clear
    this += o
    o
  }
}

class Foo extends KeyedMapper[Int,Foo] {
  object bar extends MappedOneToOne[Int,Foo,Bar]
}

f.bar.get match {
  case Some(bar) => println("Got bar")
  case _ =>
}

I might approach it by reducing the visibility of the one-to-many relationship and create a getter/setter as such:

protected object comments extends 
  MappedOneToMany(Comment, Comment.post, OrderBy(Comment.id, Ascending))

def comment : Option[Comment] = {
  comments match {
    case Nil => None
    case head :: _ => Some(head)
  }
}

def comment_=(comment: Comment) = {
  comments.clear
  comments += comment
}

Ideal? No. But more idiomatic than having client code deal with the List[Comment] instead of Option[Comment]? I think so.

Along this same line, you could also create your own class which extends MappedOneToMany. This code is untested, but I believe in the spirit of it:

class MappedOneToOne[K,T<:KeyedMapper[K, T],O <: Mapper[O]]
  (meta: MetaMapper[O], foreign: MappedForeignKey[K,O,T], qp: QueryParam[O]*) extends MappedOneToMany(meta, foreign, qp) {

  def get : Option[O] = {
    all match {
      case Nil => None
      case head :: _ => Some(head)
    }
  }

  def set(o: O) : O = {
    clear
    this += o
    o
  }
}

class Foo extends KeyedMapper[Int,Foo] {
  object bar extends MappedOneToOne[Int,Foo,Bar]
}

f.bar.get match {
  case Some(bar) => println("Got bar")
  case _ =>
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文