带有 <> 的映射投影到 Slick 中带有伴生对象的案例类 [英] Mapped projection with <> to a case class with companion object in Slick

查看:38
本文介绍了带有 <> 的映射投影到 Slick 中带有伴生对象的案例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Slick,我试图将数据库表条目直接投影到它们所代表的案例类.按照文档中的示例,我使用<> 运算符:

With Slick, I am trying to project database table entries directly to the case class they represent. Following the example in the documentation, I set up a mapped projection using the <> operator:

case class SomeEntity3(id: Int, entity1: Int, entity2: Int)

val SomeEntityTable = new Table[SomeEntity3]("some_entity_table") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def entity1 = column[Int]("entity1")
  def entity2 = column[Int]("entity2")

  def * = id ~ entity1 ~ entity2 <> (SomeEntity3, SomeEntity3.unapply _)
}

现在,我想为 SomeEntity3 添加一些静态常量和辅助方法.为此,我创建了一个伴生对象.但是只要我包含该行

Now, I'd like to add some static constants and auxiliary methods to SomeEntity3. For that, I create a companion object. But as soon as I include the line

object SomeEntity3

* 的定义弹出一个非常疯狂的多行错误,说一些关于重载方法值 <> 与替代品"的难以辨认的内容.

a pretty wild multi-line error pops up for the definition of * saying something illegible about "overloaded method value <> with alternatives".

伴随对象如何与 Slick 中的双向映射相关联,我能否以某种方式实现我的目标?

How does the companion object relate to bi-directional mapping in Slick and can I somehow accomplish my goal?

推荐答案

case 类的伴随对象通常是从 case 类的第一个参数列表到 case 类的函数.所以如果你有

Companion objects of case classes usually are a function from the case class' first argument list to the case class. So if you had

case class Fnord(a: A, b: B, c: C)(d: D)

Scala 编译器会自动生成类似于

the Scala compiler would autogenerate the companion object similar to

object Fnord extends ((A, B, C) => Fnord) {
  ...
}

现在,只要您自己明确说明有关伴随对象的某些内容,编译器就不再生成 FunctionN 扩展对象.因此,大多数时候自己添加它是个好主意.在您的情况下,这意味着像这样定义 SomeEntity3 的伴侣:

Now, as soon as you explicitly spell out something about the companion object yourself, the compiler no longer generates the FunctionN extending thingy. Thus, most of the time it is a good idea to add it yourself. In your case that would mean defining the companion of SomeEntity3 like so:

object SomeEntity3 extends ((Int, Int, Int) => SomeEntity3) {
  ...
}

这种行为也有一个(长期开放的)问题:https://issues.scala-lang.org/browse/SI-3664

There's a (long open) issue for this behaviour, too: https://issues.scala-lang.org/browse/SI-3664

这篇关于带有 &lt;&gt; 的映射投影到 Slick 中带有伴生对象的案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆