sourcecode

스칼라와 마리아를 이용한 간단한 curd rest api

codebag 2023. 8. 31. 23:52
반응형

스칼라와 마리아를 이용한 간단한 curd rest api

저는 scala에 처음 와서 마리아 데이터베이스를 이용하여 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 응답을 반환하는 방법을 누가 도와줄 수 있습니까?

언급URL : https://stackoverflow.com/questions/51763335/simple-curd-rest-api-using-scala-and-maria-db

반응형