在Slick中使用自定义列类型时进行过滤 [英] Filtering when using custom column type in Slick

查看:67
本文介绍了在Slick中使用自定义列类型时进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用自定义列类型时,在Slick 2.1.0中查询/过滤时遇到一些困难. 我的问题的简化版本:

I'm having some difficulties querying/filtering in Slick 2.1.0 when using a custom column type. A simplified version of my problem:

import scala.slick.driver.MySQLDriver.simple._

sealed class Status(val intValue: Int)
case object Active extends Status(1)
case object Disabled extends Status(2)
case object Deleted extends Status(3)

case class TableMapping(id: Long, status: Status)

class MyTableDefinition(tag: Tag) extends Table[TableMapping](tag, "sometable") {
  implicit val statusColumnType = MappedColumnType.base[Status, Int](statusToInt, intToStatus)

  def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
  def status = column[Status]("STATUS", O.NotNull, O.Default(Active))
  def * = (id, status) <> (TableMapping.tupled, TableMapping.unapply)

  private def statusToInt(s: Status): Int = s.intValue
  private def intToStatus(i: Int): Status = i match {
    case 1 => Active
    case 2 => Disabled
    case _ => Deleted
  }
}

class MyTableDao {
    val Items = TableQuery[MyTableDefinition]
    def byId(id: Long)(implicit session: Session): Option[TableMapping] = {
      Items.filter(_.status =!= Deleted).firstOption
    }
}

我在此上遇到编译错误:

I get a compile error on this:

Items.filter(_.status =!= Deleted).firstOption

错误状态:

value =!= is not a member of scala.slick.lifted.Column[Status]
[error] def byId(id: Long)(implicit session: Session): Option[TableMapping] =
  Items.filter(_.status =!= Deleted).firstOption

任何关于我做错事情的想法吗?也许有一种我不知道的更好的方法?

Any ideas of what I'm doing wrong? Maybe there is a much better way of doing this that I'm not aware of?

推荐答案

问题是Scala编译器将查找Deleted.type而不是Status的隐式转换.

The thing is that the Scala compiler will look for an implicit convertion for Deleted.type instead of Status.

由于Deleted被声明为object,所以它不是一个类,它的实际类是Deleted.type,因此您只需要帮助编译器了解它实际上是Status.如何?你可以尝试

As Deleted is declared as an object it is not a class, its actual class is Deleted.type, so you just have to help the compiler to understand that is actually a Status. How? You can try

class MyTableDao {
val Items = TableQuery[MyTableDefinition]

def byId(id: Long)(implicit session: Session): Option[TableMapping] =
    Items.filter(_.status =!= Deleted.asInstanceOf[Status]).firstOption
}

那样就可以了.

让我知道它是否确实有效,我正面临着类似的问题,并且我能够摆脱它的困扰.

Let me know if it did work, I'm facing a similar problem and I was able to get rid of it doing that.

这篇关于在Slick中使用自定义列类型时进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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