通过数据库列名访问Slick字段

时间:2016-05-02 06:59:45

标签: json scala akka slick akka-http

我有以下内容:

case class Supplier(id: Long, name: String, desc: String, sales: Int)

class SuppliersTable(tag: Tag) extends Table[Supplier](tag, "SUPPLIERS") {
  def id: Rep[Int] = column[Int]("id", O.PrimaryKey)
  def name = column[String]("name")
  def desc = column[String]("desc")
  def sales = column[Int]("sales")
  def * = (id, name, desc, sales) <> (Supplier.tupled, Supplier.unapply)
}

我需要为CRUD操作创建一个休息接口,我需要支持在列上完成的操作(更新,过滤,排序......)(每个请求可以有多个列)。数据采用JSON格式,其中JSON键是列名。

样品申请:更新供应商2的名称和销售

curl -H "Content-Type: application/json" -X PUT -d '{
  "name": "newSupplierName",
  "sales" : 100
}' localhost:8080/supplier/2

如何通过了解JSON请求中的列名来告诉slick哪个字段更新?

我的初步计划是从JSON有效负载生成纯SQL查询:

休息路线:

private val supplierUpdateRoute = path("supplier" / IntNumber) { (supId) =>
  put {
    entity(as[String]) { supplierToUpdate => 
      import spray.json._

      val jsonAst = supplierToUpdate.parseJson
      val jsonMap = jsonAst.asJsObject.fields

      onComplete((modules.suppliersDal.update(jsonMap, supId))) {
      // ignoring the number of insertedEntities because in this case it should always be one, you might check this in other cases
      case Success(insertedEntities) => complete(Created)
      case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}")
      }
    }
  }
}

DAL班级:

def update(jsonMap : Map[String, JsValue], id: Long): Future[Unit] = {

  val tableName = tableQ.baseTableRow.tableName
  //val columns = tableQ.baseTableRow.create_*.map(_.name).toSeq

  val listQuery = jsonMap.foldLeft[List[String]](Nil)((acc, head) => acc :+ s"${head._1} = ${head._2}") 
  val fieldsToUpdate = listQuery.mkString(", ")
  val baseQuery = sqlu"update #${tableName} set #$fieldsToUpdate where id = #$id"


  db.run(DBIO.seq(baseQuery))
}

当SuppliersTable类中定义的columnName为小写

时,我收到了一些未找到列的错误

ServerLog中:

1: StreamingInvokerAction$HeadAction [update SUPPLIERS set name = "newSupplierName", sales = 100 where id = 2]
2: success ()

ConsoleLog:

An error occurred: Column "NAME" not found; SQL statement:
update SUPPLIERS set name = "newSupplierName", sales = 100 where id = 2

如果我将列名设置为所有CAPS,我正在

An error occurred: Column "newSupplierName" not found; SQL statement:
update SUPPLIERS set name = "newSupplierName", sales = 1000 where id = 2 

我不知道从JSON创建普通的sql查询是否是个好主意。你能建议一个更好的方法吗?即使表格在将来被更改(添加/删除新列......),我也需要我的api才能工作。

使用的模板来自Lightbend - link

修改

看起来像slick识别字符串封装在“”作为列名,

通过将'\''替换为'\'',将json字符串值作为字符串文字而不是列名称进行了解决方法:

val listQuery = jsonMap.foldLeft[List[String]](Nil)((acc, head) => acc :+ s"${head._1} = ${head._2}") 

val fieldsToUpdate = listQuery.mkString(", ").replace('\"', '\'')

仍然可以提出建议,因为我对我的解决方案仍然没有信心

0 个答案:

没有答案