如何将Slick结果转换为所需格式?

时间:2019-04-30 10:18:27

标签: scala akka h2 akka-http slick-3.0

我有类型为 Checkbox1 - Annot1 - Mouseup - Action1 的域对象,它在案例类中定义如下:

Person

和相应的查询表如下:

case class Person(personName: String, personAge: Int, personId: Long = 0)

并且我有类型final case class PersonTable(tag: Tag) extends Table[Person](tag, "people") { def personId = column[Long]("person_id", O.AutoInc, O.PrimaryKey) def personName = column[String]("person_name") def age = column[Int]("person_age") def * = (personName, age, personId).mapTo[Person] } 的域对象,它在案例类中定义如下:

Address

其对应的表类定义如下。人与地址具有一对多关系( 一个人可以有多个地址,但一个地址仅属于一个人

case class Address(houseNumber: Int, street: String
, state: String, ownerId: Long, id: Long = 0)

我想从基于final case class AddressTable(tag: Tag) extends Table[Address](tag, "addresses") { def houseNumber = column[Int]("house_number") def street = column[String]("street_name") def state = column[String]("state_name") def addressId = column[Long]("address_id", O.PrimaryKey, O.AutoInc) def ownerId = column[Long]("owner_id") def owner = foreignKey("owner_fk", ownerId, TableQuery[PersonTable])(_.personId, onDelete = ForeignKeyAction.Cascade) def * = (houseNumber, street, state, ownerId, addressId).mapTo[Address] } 的REST API中返回以下类型的JSON结果(地址应作为数组返回):

Akka-http

要获得此结果,我使用Slick编写了查询,如下所示:

{
    "name": "shekhar",
    "age": 30,
    "id": 1234,
    "addresses": [{
            "house_number": 1,
            "street": "water street",
            "state": "foo bar",
            "owner_id": 1234,
            "address_id": 9874
        },
        {
            "house_number": 99,
            "street": "foo bar street",
            "state": "foo disk state",
            "owner_id": 1234,
            "address_id": 007
        }
    ]
}

我得到以下结果的结果(每个地址的人员详细信息):

  val peopleQueries = TableQuery[PersonTable]
  val addressQueries = TableQuery[AddressTable]
  val query = peopleQueries.filter(_.personName === "Shekhar") joinLeft addressQueries on (_.personId === _.ownerId)
  val futureResultData = db.run(query.result)

要将以上内容转换为预期的JSON格式,我可以等到数据库查询运行后再编写一些Scala代码以使其达到所需的格式,但这将阻止请求,直到此后处理完成为止(如果我对此有误)。

我的代码如下所示:

Vector(
  (Person("shekhar",30,1234),
    Some(Address(1,"Water Street","foo bar",1234,9874))
  )
  , (Person("shekhar",30,1234),
    Some(Address(99,"foo bar street","foo disk state",1234,007))
  )
)

我想知道是否有任何方法可以得到非随机/非阻塞方式的结果


感谢Pedro,我找到了解决此问题的方法。

对我有用的解决方案如下:

futureResultData.onComplete {
  case Success(data) => // code to bring data in desired format
}

1 个答案:

答案 0 :(得分:2)

futureResultData.map {
  _.transformInDesiredFormat // code to bring data in desired format
}

如果您发布的是可以转化的实际代码,我可以为您提供更多帮助

未来是单子,所以当您映射时,您将使用该未来中的东西。如果您拥有Future [Int],并且将其映射到未来中,那么您将与Int一起使用。

示例:

val aFuture = Future.successful(1)
aFuture.map(f=>  f+ 1)