PlayFrameWork2.5+Scala+Eclipse+PlaySlick+MySQL을 Windows10에서 사용해 보았습니다.

17238 단어 PlayFramework

소개



환경 구축은 여기 를 참조

이번에는 여기에 MySQL을 추가한 것을 준비
  • MySQL5.6

  • (60 분 요리) Play Framework (Scala) + MySQL로 REST API 서버 만들기

    이것을 바탕으로 PlayFrameWork를 사용해 본다.

    즉시 문제가 발생



    build.sbt에 anorm를 추가하고 activator eclipse 명령에서
    필요한 파일 다운로드
    C:\framework\play\playScalaTest>activator eclipse
    ACTIVATOR_HOME=C:\framework\activator-1.3.10-minimal
    ファイル BIN_DIRECTORY\..\conf\sbtconfig.txt が見つかりません。
    [info] Loading project definition from C:\framework\play\playScalaTest\project
    Anorm has been moved to an external module.
    See https://playframework.com/documentation/2.4.x/Migration24 for details.
    Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?
    

    htps : // p ぁ yf 라메를 rk. 코m/도쿠멘 타치온/2.4. x/미g라치온 24
    htps : // p ぁ yf 라메를 rk. 코m/도쿠멘 타치온/2.4. x/그 rm

    PlayFrameWork2.4부터 anorm은 play의 코어에서 잘라지기 때문에,
    그대로는 사용할 수없는 것 같습니다.

    모처럼이므로 방향 전환하고 PlaySlick을 사용해보기

    참고 정보



    Scala on Play에서 API 서버 구축 with MySQL

    해설도 알기 쉬웠으므로 여기를 참고로 사경해 본다

    라우팅 설정


    GET /client  controllers.HomeController.client
    

    컨트롤러 설정



    playScalaTest\controllers\HomeController.scala
    package controllers
    
    import javax.inject._
    import play.api._
    import play.api.mvc._
    // importを追加
    import play.api.libs.json.Json
    
    /**
     * This controller creates an `Action` to handle HTTP requests to the
     * application's home page.
     */
    @Singleton
    class HomeController @Inject() extends Controller {
    
      /**
       * Create an Action to render an HTML page with a welcome message.
       * The configuration in the `routes` file means that this method
       * will be called when the application receives a `GET` request with
       * a path of `/`.
       */
      def index = Action {
        Ok(views.html.index("Your new application is ready."))
      }
      // Actionを追加
      def client = Action {
        val json = Json.obj("client" -> "Hello!");
    
        Ok(Json.toJson(json));
      }
    }
    

    MySQL 설정



    client 테이블 만들기
    CREATE TABLE `client` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `name` text NOT NULL,
      `address` text NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    적절한 데이터를 등록하십시오.

    모듈 추가



    MySQL-Connector 및 Play-Slick 추가

    playScalaTest\build.sbt
    name := """playScalaTest"""
    
    version := "1.0-SNAPSHOT"
    
    lazy val root = (project in file(".")).enablePlugins(PlayScala)
    
    scalaVersion := "2.11.7"
    
    libraryDependencies ++= Seq(
      jdbc,
      cache,
      ws,
      "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test,
      "mysql" % "mysql-connector-java" % "5.1.39",
      "com.typesafe.play" %% "play-slick" % "2.0.0"
    )
    
    resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"
    
    

    명령 프롬프트에서 Eclipse에 추가
    C:\framework\play\playScalaTest>activator eclipse
    ACTIVATOR_HOME=C:\framework\activator-1.3.10-minimal
    ファイル BIN_DIRECTORY\..\conf\sbtconfig.txt が見つかりません。
    [info] Loading project definition from C:\framework\play\playScalaTest\project
    [info] Set current project to playScalaTest (in build file:/C:/framework/play/playScalaTest/)
    [info] About to create Eclipse project files for your project(s).
    [info] Updating {file:/C:/framework/play/playScalaTest/}root...
    [info] Resolving jline#jline;2.12.1 ...
    [info] downloading https://repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar ...
    [info]  [SUCCESSFUL ] mysql#mysql-connector-java;5.1.39!mysql-connector-java.jar (1789ms)
    [info] Done updating.
    [info] Successfully created Eclipse project files for project(s):
    [info] playScalaTest
    

    데이터베이스 설정



    데이터베이스 설정 추가

    playScalaTest\conf\application.conf
    slick.dbs.default.driver="slick.driver.MySQLDriver$"
    slick.dbs.default.db.driver="com.mysql.jdbc.Driver"
    slick.dbs.default.db.url="jdbc:mysql://localhost:3306/test?user=[ユーザー名]&password=[パスワード]"
    

    모델 정의



    playScalaTest\models\database\Client.scala
    package models.database
    
    import play.api.libs.json.Json
    
    case class Client (
      id: Option[Long],
      name: String,
      address: String
    )
    
    object Client {
      implicit val clientWrites = Json.writes[Client]
      implicit val clientReads = Json.reads[Client]
    }
    

    DAO 정의



    playScalaTest\models\ClientDAO.scala
    package models
    
    import javax.inject.Singleton
    import javax.inject.Inject
    import play.api.db.slick.DatabaseConfigProvider
    import slick.driver.JdbcProfile
    import scala.concurrent.impl.Future
    import scala.concurrent.Future
    
    import models.database.Client
    import play.api.libs.concurrent.Execution.Implicits.defaultContext
    import play.api.libs.json
    
    @Singleton
    class ClientDAO @Inject()(val dbConfigProvider: DatabaseConfigProvider) {
    
      val dbConfig = dbConfigProvider.get[JdbcProfile]
    
      import dbConfig.driver.api._
    
      private class ClientTable(tag: Tag) extends Table[Client](tag, "client") {
        def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
        def name = column[String]("name")
        def address = column[String]("address")
    
        def * = (id.?, name, address) <> ((Client.apply _).tupled, Client.unapply)
      }
    
      private val clients = TableQuery[ClientTable]
    
      def all(): Future[List[Client]] = dbConfig.db.run(clients.result).map(_.toList)
    }
    

    API 구현



    playScalaTest\app\controllers\HomeController.scala
    package controllers
    
    import javax.inject._
    import play.api._
    import play.api.mvc._
    import play.api.libs.json.Json
    
    import models.database.Client
    import models.ClientDAO
    
    // Futureを扱うにはこの2つのimportが必要
    import scala.concurrent._
    import scala.concurrent.ExecutionContext.Implicits.global
    
    /**
     * This controller creates an `Action` to handle HTTP requests to the
     * application's home page.
     */
    @Singleton
    class HomeController @Inject() (dao: ClientDAO) extends Controller {
    
      /**
       * Create an Action to render an HTML page with a welcome message.
       * The configuration in the `routes` file means that this method
       * will be called when the application receives a `GET` request with
       * a path of `/`.
       */
      def index = Action {
        Ok(views.html.index("Your new application is ready."))
      }
      // APIの処理を書き直し
      def client = Action.async {
        dao.all().map(clients => Ok(Json.toJson(Json.toJson(clients))))
      }
    }
    

    Eclipse 컴파일



    명령 프롬프트에서 실행
    c:\framework\play\playScalaTest>activator eclipse compile
    ACTIVATOR_HOME=C:\framework\activator-1.3.10-minimal
    ファイル BIN_DIRECTORY\..\conf\sbtconfig.txt が見つかりません。
    [info] Loading project definition from C:\framework\play\playScalaTest\project
    [info] Set current project to playScalaTest (in build file:/C:/framework/play/playScalaTest/)
    [info] About to create Eclipse project files for your project(s).
    [info] Successfully created Eclipse project files for project(s):
    [info] playScalaTest
    [info] Compiling 7 Scala sources and 1 Java source to C:\framework\play\playScalaTest\target\scala-2.11\classes...
    [success] Total time: 9 s, completed 2016/06/29 21:26:45
    

    실행 결과



    좋은 웹페이지 즐겨찾기