简体   繁体   English

Slick:ClassCastException:scala.Some无法转换为java.lang.String

[英]Slick: ClassCastException: scala.Some cannot be cast to java.lang.String

First, I have to mention I am still pretty new to Slick, and mostly learning and every time discovering some weird cases, like this. 首先,我不得不提一下,我还是Slick的新手,主要学习和每次发现一些奇怪的情况,例如这样。

I have a case class Address define for Slick table as follows: 我为Slick表定义了一个案例类Address,如下所示:

package model

import driver.PGDriver.api._
import format.DateTimeFormat._
import org.joda.time.DateTime
import play.api.libs.json._
import slick.lifted.Tag

case class Address(id: Option[Int] = None,
                   countryId: Option[Int] = None,
                   continentId: Option[Int] = None,
                   stateId: Option[Int] = None,
                   address1: String,
                   address2: Option[String],
                   city: String,
                   zip: String,
                   createdAt: DateTime = DateTime.now,
                   updatedAt: DateTime = DateTime.now,
                   deletedAt: Option[DateTime] = None,
                   createdBy: Option[String] = None,
                   updatedBy: Option[String] = None)

object Addresses {

  val addresses = TableQuery[Addresses]

  implicit lazy val addressFormat: Format[Address] = Json.format[Address]

  Json.toJson[DateTime](DateTime.now)

}

class Addresses(tag: Tag) extends Table[Address](tag, "address") {

  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)

  def countryId = column[Option[Int]]("country_id")
  def continentId = column[Option[Int]]("continent_id")
  def stateId = column[Option[Int]]("state_id")

  def address1 = column[String]("address1", O.SqlType("character varying(255)"))
  def address2 = column[Option[String]]("address1", O.SqlType("character varying(255)"))
  def city = column[String]("city", O.SqlType("character varying(255)"))
  def zip = column[String]("zip", O.SqlType("character varying(30)"))

  def createdAt = column[DateTime]("createdat")
  def updatedAt = column[DateTime]("updatedat")
  def deletedAt = column[Option[DateTime]]("deletedat")

  def createdBy = column[Option[String]]("createdby", O.SqlType("character varying(255)"))
  def updatedBy = column[Option[String]]("updatedby", O.SqlType("character varying(255)"))

  override def * =
    (
      id.?,
      countryId,
      continentId,
      stateId,
      address1,
      address2,
      city,
      zip,
      createdAt,
      updatedAt,
      deletedAt,
      createdBy,
      updatedBy
    ) <> (Address.tupled, Address.unapply)

  def addressStateIdIdx = index("address_state_id_idx", stateId)
  def state =
    foreignKey("address_state_id_fkey", stateId, GeoAreas.areas)(
      _.id.?,
      onUpdate = ForeignKeyAction.Cascade,
      onDelete = ForeignKeyAction.Restrict
    )

  def addressCountryIdIdx = index("address_country_id_idx", countryId)
  def country =
    foreignKey("address_country_id_fkey", countryId, GeoAreas.areas)(
      _.id.?,
      onUpdate = ForeignKeyAction.Cascade,
      onDelete = ForeignKeyAction.Restrict
    )

  def addressContinentIdIdx = index("address_continent_id_idx", continentId)
  def continent =
    foreignKey("address_continent_id_fkey", continentId, GeoAreas.areas)(
      _.id.?,
      onUpdate = ForeignKeyAction.Cascade,
      onDelete = ForeignKeyAction.Restrict
    )

}

This is not my only class with works through Slick, but, for some reason, only because of this class I am getting an exception when trying to create a query with join. 这不是我的唯一一个通过Slick进行工作的类,但是由于某种原因,仅由于这个类,当尝试使用join创建查询时,我遇到了异常。 Like so: 像这样:

def search(searchCriteria: SearchCriteria,
             readyOnly: Boolean,
             drop: Long = 0,
             take: Long = 100): Future[Seq[(School, Option[Address])]] = {
    val q = for {
      (school, address) <- Schools.schools joinLeft Addresses.addresses on (_.addressId === _.id)
      if List(
        Some(school.deletedAt.isEmpty),
        searchCriteria.school.name.map(n => school.name.toLowerCase like s"%${n.toLowerCase}%"),
        searchCriteria.school.ready.map(r => school.ready === r)
      ).collect({ case Some(criteria) => criteria }).reduceLeftOption(_ && _).getOrElse(true: Rep[Boolean])
    } yield (school, address)

    db.run(q.drop(drop).take(take).result)
  }

The exception I am getting is: play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[ClassCastException: scala.Some cannot be cast to java.lang.String]] 我得到的异常是: play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[ClassCastException: scala.Some cannot be cast to java.lang.String]]

在此处输入图片说明

At this particular point, I don't even have a slight idea where to start looking for a problem. 在这一点上,我什至不知道从哪里开始寻找问题。 This class is very similarly defined to the other classes I have. 该类的定义与我所拥有的其他类非常相似。 All others work fine. 所有其他人都很好。 Everything compiles without a problem. 一切编译都没有问题。 The exception is thrown in runtime only. 仅在运行时中引发异常。

What am I missing? 我想念什么? Thanks, 谢谢,

UPDATE UPDATE

I might have found the problem, however, I am not sure how to fix it and why is it happening. 我可能已经找到了问题,但是我不确定如何解决它以及为什么会发生。 The actual query that is getting executed is this: 正在执行的实际查询是这样的:

SELECT
  x2."id",
  x2."address_id",
  x2."name",
  x2."about",
  x2."number_of_students",
  x2."website_url",
  x2."media_id",
  x2."slug",
  x2."short_description",
  x2."ready",
  x2."classrooms",
  x2."year_established",
  x2."display_copyright",
  x2."createdat",
  x2."updatedat",
  x2."deletedat",
  x2."createdby",
  x2."updatedby",
  x2."dli_number",
  (CASE WHEN (x3."id" IS NULL)
    THEN NULL
   ELSE 1 END),
  x3."id",
  x3."country_id",
  x3."continent_id",
  x3."state_id",
  x3."address1",
  x3."address1",
  x3."city",
  x3."zip",
  x3."createdat",
  x3."updatedat",
  x3."deletedat",
  x3."createdby",
  x3."updatedby"
FROM "school" x2 LEFT OUTER JOIN "address" x3 ON x2."address_id" = x3."id"
WHERE ((x2."deletedat" IS NULL) AND (lower(x2."name") LIKE '%a%')) AND (x2."ready" = TRUE)
LIMIT 100
OFFSET 0

There is some weird case as part of the select. 作为选择的一部分,有些奇怪的case Why is it there? 为什么在那儿? what am I doing wrong? 我究竟做错了什么?

UPDATE #2 更新#2

From the other hand, not knowing exactly how slick reads the rows of the query, I am not sure if this case statement could cause the original problem. 另一方面,由于不知道如何精确地读取查询的行,因此我不确定此case语句是否会导致原始问题。

But, I am still stuck. 但是,我仍然被困住。

UPDATE #3 更新#3

So, I just tried the simplest query possible that includes only the address table, like so: 因此,我只是尝试了可能的最简单查询,该查询仅包含地址表,如下所示:

def all(): Future[Seq[Address]] = db.run(Addresses.addresses.filter(_.deletedAt.isEmpty).result)

And I am still getting the same exception. 而且我仍然遇到同样的例外。

Update #4 更新#4

Here is the actual address table: 这是实际的地址表:

create table address
(
    id bigserial not nullconstraint address_pkey primary key,
    country_id bigint constraint address_country_id_fkey references geo_area on update cascade on delete restrict,
    continent_id bigint constraint address_continent_id_fkey references geo_area on update cascade on delete restrict,
    state_id bigint constraint address_state_id_idx references geo_area on update cascade on delete restrict,
    address1 varchar(255) not null,
    address2 varchar(255),
    city varchar(255) not null,
    zip varchar(30) not null,
    deletedat timestamp with time zone,
    createdat timestamp with time zone not null,
    updatedat timestamp with time zone not null,
    createdby varchar(255),
    updatedby varchar(255)
);

create index address_country_id_idx on address (country_id);

create index address_continent_id_idx on address (continent_id);

create index address_state_id_idx on address (state_id);

I had a feeling that it is something really stupid, and I was right. 我有种感觉,那真是愚蠢,我是对的。 @Tyler, thanks for pointing me in the right direction The problem was here: @Tyler,感谢您为我指明了正确的方向问题出在这里:

def address1 = column[String]("address1", O.SqlType("character varying(255)"))
  def address2 = column[Option[String]]("address1", O.SqlType("character varying(255)"))

Look at how the address2 is defined. 看一下address2是如何定义的。 these two had duplicate column names. 这两个具有重复的列名。 so obviously it was suppose to be: 因此显然应该是:

def address1 = column[String]("address1", O.SqlType("character varying(255)"))
  def address2 = column[Option[String]]("address2", O.SqlType("character varying(255)"))

The exception is, as usual, useless :) 和往常一样,例外是无用的:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 scala.Some无法强制转换为java.lang.String - scala.Some cannot be cast to java.lang.String scala。一些不能转换为自定义对象 - scala.Some cannot be cast to custom object java.lang.ClassCastException:java.lang.String 无法转换为 java.lang.Float - java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Float java.lang.ClassCastException:无法将java.lang.String强制转换为com.fastdata.persistence.PersistenceService - java.lang.ClassCastException: java.lang.String cannot be cast to com.fastdata.persistence.PersistenceService java.lang.ClassCastException:[B在解析json [String,String]时不能转换为java.lang.String - java.lang.ClassCastException: [B cannot be cast to java.lang.String while parsing json[String,String] java.lang.String 不能转换为 scala.Serializable - java.lang.String cannot be cast to scala.Serializable Scala 转换问题:java.lang.String 无法转换为 scala.runtime.Nothing - Scala Cast Issues : java.lang.String cannot be cast to scala.runtime.Nothing kafka Producer上的“ ClassCastException:kafka.message.Message无法转换为java.lang.String” - “ClassCastException: kafka.message.Message cannot be cast to java.lang.String” on kafka Producer java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record 不能转换为 java.lang.String - java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to java.lang.String 将JsObject保存到JSON文件(无法将java.lang.String强制转换为scala.scalajs.js.Any) - Save a JsObject to JSON file (java.lang.String cannot be cast to scala.scalajs.js.Any)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM