使用scala和maria db的简单豆腐休息api

时间:2018-08-09 09:23:40

标签: scala intellij-idea mariadb

我是scala的新手,想使用maria数据库创建REST API

这是我的模型课

package Model
import play.api.Play
import play.api.data.Form
import play.api.data.Forms._
import slick.jdbc.H2Profile.api._
import scala.concurrent.Future
import slick.driver.JdbcProfile

import scala.concurrent.ExecutionContext.Implicits.global

case class User(id: Long, firstName: String, lastName: String, mobile: Long, email: String)
case class UserFormData(firstName: String, lastName: String, mobile: Long, email: String)



object UserForm {

  val form = Form(
    mapping(
      "firstName" -> nonEmptyText,
      "lastName" -> nonEmptyText,
      "mobile" -> longNumber,
      "email" -> email
    )(UserFormData.apply)(UserFormData.unapply)
  )
}

object Users
{
  val dbConfig = Database.forURL("jdbc:mariadb://localhost:3306/scalatest?user=root&password=123456", driver = "org.mariadb.jdbc.Driver")
  //val dbConfig1 = dbConfig.get[JdbcProfile](Play.current)
  val users = TableQuery[UserTableDef]
  def delete(id: Long): Future[Int] = {
    dbConfig.run(users.filter(_.id === id).delete)
  }
//def delete(id: Long): Future[Int] = {
//  val originalSize = users.length
//  users = users.filterNot(_.id == id)
//  Some(originalSize - users.length) // returning the number of deleted users
//}

  def get(id: Long): Future[Option[User]] = {
    dbConfig.run(users.filterNot(_.id === id).result.headOption)
  }
}

class UserTableDef(tag: Tag) extends Table[User](tag, "user") {

  def id = column[Long]("id", O.PrimaryKey,O.AutoInc)
  def firstName = column[String]("first_name")
  def lastName = column[String]("last_name")
  def mobile = column[Long]("mobile")
  def email = column[String]("email")

  override def * =
    (id, firstName, lastName, mobile, email) <>(User.tupled, User.unapply)
}

这是我的服务等级

package Services
import Model.User

import scala.concurrent.Future

import Model.{User,Users}





object UserService {
//    def addUser(user: User): Future[String] = {
//      User.apply()
//    }
  //
    def deleteUser(id: Long): Future[Int] = {
      Users.delete(id)
    }
  //
    def getUser(id: Long): Future[Option[User]] = {
      Users.get(id)
    }
  //
  //  def listAllUsers: Future[Seq[User]] = {
  //    Users.listAll
  //  }
  //}
}

这是我的控制器类

package controllers

import Services.UserService
import play.api.mvc.{Action, Controller}
/**
  * A very small controller that renders a home page.
  */
import Model.User
import Services.UserService
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.libs.json.Json
class HomeController extends Controller {

  def index = Action { implicit request =>
    Ok(views.html.index())
  }

  def deleteUser(id: Long) = Action.async { implicit request =>
    UserService.deleteUser(id) map { res =>
      Ok(Json.toJson(1))
    }
  }
  def getPersons(id:Long)  = Action.async { implicit request =>
    UserService.getUser(id) map { res=>
      Ok(Json.toJson(1))
    }
  }
}

路线

GET        /                       controllers.HomeController.index

->         /v1/posts               v1.post.PostRouter
GET     /delete/:id                 controllers.HomeController.deleteUser(id : Long)
GET     /getPersons/:id                     controllers.HomeController.getPersons(id : Long)
# Map static resources from the /public folder to the /assets URL path
GET        /assets/*file        controllers.Assets.at(path="/public", file)

当我使用sbt run运行此代码并尝试从ID为1的表中删除用户时,出现此异常

Caused by: java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '"user" where "user"."id" = 1' at line 1
Query is: delete from "user" where "user"."id" = 1
        at org.mariadb.jdbc.internal.util.LogQueryTool.exceptionWithQuery(LogQueryTool.java:153)
        at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:255)
        at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeInternal(MariaDbPreparedStatementClient.java:209)
        at org.mariadb.jdbc.MariaDbPreparedStatementClient.execute(MariaDbPreparedStatementClient.java:150)
        at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeUpdate(MariaDbPreparedStatementClient.java:183)
        at slick.jdbc.JdbcActionComponent$DeleteActionExtensionMethodsImpl$$anon$4$$anonfun$4.apply(JdbcActionComponent.scala:270)
        at slick.jdbc.JdbcActionComponent$DeleteActionExtensionMethodsImpl$$anon$4$$anonfun$4.apply(JdbcActionComponent.scala:268)
        at slick.jdbc.JdbcBackend$SessionDef$class.withPreparedStatement(JdbcBackend.scala:371)
        at slick.jdbc.JdbcBackend$BaseSession.withPreparedStatement(JdbcBackend.scala:433)
        at slick.jdbc.JdbcActionComponent$DeleteActionExtensionMethodsImpl$$anon$4.run(JdbcActionComponent.scala:268)

任何人都可以帮助我解决此问题,以及如何从JSON返回响应,例如,如果我正在编写一些函数来从数据库中获取所有用户

0 个答案:

没有答案