Typesafe Activator

Super Slick Play

Super Slick Play

mkelland
Source
December 24, 2013
basics play java scala starter slick

Slick (the Scala Language-Integrated Connection Kit) is a framework for type safe, composable data access in Scala. This template combines Play Framework with Slick for quick start Slick integrated database-backed web application development.

How to get "Super Slick Play" on your computer

There are several ways to get this template.

Option 1: Choose play-slick in the Typesafe Activator UI.

Already have Typesafe Activator (get it here)? Launch the UI then search for play-slick in the list of templates.

Option 2: Download the play-slick project as a zip archive

If you haven't installed Activator, you can get the code by downloading the template bundle for play-slick.

  1. Download the Template Bundle for "Super Slick Play"
  2. Extract the downloaded zip file to your system
  3. The bundle includes a small bootstrap script that can start Activator. To start Typesafe Activator's UI:

    In your File Explorer, navigate into the directory that the template was extracted to, right-click on the file named "activator.bat", then select "Open", and if prompted with a warning, click to continue:

    Or from a command line:

     C:\Users\typesafe\play-slick> activator ui 
    This will start Typesafe Activator and open this template in your browser.

Option 3: Create a play-slick project from the command line

If you have Typesafe Activator, use its command line mode to create a new project from this template. Type activator new PROJECTNAME play-slick on the command line.

Option 4: View the template source

The creator of this template maintains it at https://github.com/mkelland/activator-play-slick#master.

Option 5: Preview the tutorial below

We've included the text of this template's tutorial below, but it may work better if you view it inside Activator on your computer. Activator tutorials are often designed to be interactive.

Preview the tutorial

You've just created an application with the Super Slick Play template. The template allows you to quickly create a Play application using Slick for database access. The template has been pre-configured to use an in-memory database called H2.

Set up the database

The template you're using is already set up with an in-memory instance of the H2 database. You can leave this as it is and skip this section if you want to continue using this database.

It is sometimes advantageous to use H2 in file mode rather than in memory. This will allow debugging through things like the h2-browser or other methods of access to H2. To make this change, edit the conf/application.conf file and find the line that specifies the default url :

db.default.url="jdbc:h2:mem:play"
In order to use a file-based database, change this to
db.default.url="jdbc:h2:/path/to/file
You can then get access to the database by shutting down any processes (including Play) that are accessing it and using the following commands
play
h2-browser
And then enter the same URL to access H2.

To use a different database technology, use the instructions on the Play Documentation site

Create tables

Play includes a function called evolutions that allows the management of database schema changes. To use evolutions, create an evolutions folder for the default database as conf/evolutions/default then create .sql scripts that will put the database into the appropriate state. Evolutions also has the ability to revert the database to a previous version. For example, create a file called conf/evolutions/default/1.sql with the following content:


# Resources schema
 
# --- !Ups
 
CREATE TABLE Resource (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    first varchar(255) NOT NULL,
        last varchar(255) NOT NULL,
    PRIMARY KEY (id)
);
 
# --- !Downs
 
DROP TABLE Resource;
When you load up your application, you will be prompted to apply the script(s).

Create the models

In order to create a set of models in play that will use Slick to access the database, you need to create the models. The Slick site at slick.typesafe.com has an excellent set of documentation.

To create a model to access our "Resource" table, create a file in app/models called Resource.scala


		package models
// Importing the slick driver
import play.api.db.slick.Config.driver.simple._

// The case class to represent the data object
case class Resource(id: Option[Int] = None, first: String, last: String)

// The static object that does the actual work - note the names of tables and fields in H2 are case sensitive and must be all caps 
object Resources extends Table[Resource]("RESOURCE") {
  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def first = column[String]("FIRST")
  def last = column[String]("LAST")

  // Every table needs a * projection with the same type as the table's type parameter
  def * = id.? ~ first ~ last <> (Resource, Resource.unapply _)

  // This custom insert method allows the return of the auto increment id when the row is inserted without specifying it
  def forInsert = first ~ last  <> ({ t => Resource(None, t._1, t._2)}, { (r: Resource) => Some ((r.first, r.last))})
}

Some important items to note - H2 capitalizes all table and column names and is case sensitive

Insert some initial data

If you want to put some initial data into the table we created, create a file called Global.scala in the app directory with the following content

 
	import play.api.db.DB
import play.api.GlobalSettings
// Use H2Driver to connect to an H2 database
import play.api.db.slick.Config.driver.simple._



import play.api.Application
import play.api.Play.current

import models._


object Global extends GlobalSettings {

  override def onStart(app: Application) {

    InitialData.insert()
  
  }

object InitialData {

	
	def insert() = {
	  
	 
		play.api.db.slick.DB.withSession { 
		  implicit session:Session =>
              val resourceOneId = Resources.forInsert returning Resources.id insert(Resource(None, "Great", "Engineer"))
		}
	}
    }
}
	

View the App

Once the application has been compiled and the server started, your application can be accessed at: http://localhost:9000
Check in Run to see the server status.
When you make an HTTP request to that URL, the Play server figures out what code to execute which will handle the request and return a response. In this application the request handler for requests to the root URL (e.g. "/") are handled by a Java Controller. You can use Java and Scala to create your controllers.
Controllers asynchronously return HTTP responses of any content type (i.e. HTML, JSON, binary). To see a JSON response produced by a Scala controller, click the "Get JSON Message" button. This uses AJAX via jQuery to get data from the server and then display that on the web page.

Code Overview

A Play application has very few required files. This example tries to illustrate a number of key concepts in Play so it has a handful of files to explain. The app directory contains the application's source code, including Java, Scala, server-side templates, and server-side compiled assets for the browser (e.g. JavaScript, CoffeeScript, LESS). The conf directory contains the application.conf config file and the routes file. The project directory contains the SBT build information for the app. The default place for static assets (e.g. images, HTML, CSS, JavaScript) is the public directory. Unit, functional, and integration tests (Java and Scala) go in the test directory.

HTTP Routing

The routes file contains mappings between HTTP request verbs & paths and the code that controller method that handles the requests. Route paths can be parametrized to support RESTful style URLs. The following mapping will handle HTTP GET requests to "/" using the controllers.MainController.index method:

GET   /    controllers.MainController.index
You can try out the routing by first making a request to an unmatched route, like: http://localhost:9000/foo
This should produce an error because there isn't a route that matches the request. Then edit the routes to include a new route:
GET   /foo    controllers.MainController.index
Now retry the request and you should see the default index page.
By default the routes are compiled by Play so that they can be used in a type-safe way. This prevents issues caused by incorrect URL usages.

Controllers

HTTP GET requests to http://localhost:9000/ are handled by the index method defined in the MainController.java file. This static method returns a Result which in this case consists of a server-side rendered template and an HTTP 200 response which is represented by the ok method call. You can also use non-static methods along with Dependency Injection frameworks like Spring, Guice, and CDI.
You can change the "Hello from Java" string in MainController.java a different value, like "Hello from Play", then save the file and reload the index page in your browser. Play will automatically recompile the controller and you should immediately see your changes.
If your changes result in a compile error you will see the error in your browser (after a refresh) and in the Compile Plugin. Try it by removing one of the double-quotes in the index method's string, save the file, and reload the index page. Fix the error before you continue.
There is also a Scala controller which provides an example JSON service. (Note: Play also has built-in JSON support in Java controllers.) You can see the JSON by opening http://localhost:9000/message in your browser. This route is also mapped in the routes file but this time the request is handled by the MessageController.scala file's getMessage function. This controller returns an Action which is responsible for producing a HTTP response. In this case the response is a case class which is serialized to JSON. You will also notice the MessageController contains a function called javascriptRoutes which provides a mechanism for using the type-safe routes in JavaScript.

Templates

The MainController.index method uses a template which is compiled by Play into a function. The source is in the index.scala.html file and is available by calling the views.html.index.render function. This template takes a parameter of a String so the compiled function also takes a String parameter. The default templating language in Play is Scala, but a number of other templating languages (like Java, Groovy, and Dust) can also be plugged in.
The index template uses the main template by calling the main function with the required parameters.
Notice that the templates do not use hard-coded URLs and instead use Play's reverse routing, like:

@routes.Assets.at("images/favicon.png")
This provides a type-safe way to specify URLs in an application. If the URL to a file changes, then automatically, the new value will be used throughout all of the URL references. You can use the reverse router anywhere in your code, like redirects in controllers.
Like controllers (and all source code in Play) you can make changes to templates which triggers a recompile. Then simply refresh the page to see the changes. Try it out by making a change to the index template, saving the file, and then refreshing the index page in your browser.

Static Assets

This application has a route to handle loading static assets from the public directory:

GET /assets/*file controllers.Assets.at(path="/public", file)
A request to http://localhost:9000/assets/images/favicon.png will use this route to find the favicon.png file in the public/images directory.
You can put any static assets into the public directory and have them accessible in this way.

Asset Compiler

Modern web applications often use compilers to generate static assets for the browser. Play has a built-in asset compiler which can automatically syntax check & minify JavaScript, compile CoffeeScript to JavaScript, and compile LESS to CSS. You can also plug in other compilers into the Play's asset compiler.
This application contains two example uses of the asset compiler. The index.js file will automatically be syntax checked and minified. The minified version is can be referenced in a template with:

<script type='text/javascript'
src='@routes.Assets.at("javascripts/index.min.js")'>
</script>
You can also put CoffeeScript files with a .coffee extension in the app/assets/javascripts directory to have them automatically compiled and minified.
The index.less file will be compiled into both a index.css and a index.min.css file.

Test the App

This application includes a number of tests which are automatically run after each successful compile. You can see the test results in the Test plugin. Due to changes that you may have made to your application source code, some of the tests might now be failing. The source for the tests is located in the test directory and contains both Java and Scala tests. The test/MainControllerTest.java Java class contains a number of unit and functional tests for the MainController. The IntegrationTest.java file contains an test which uses Solenium to test the actual UI in a browser. The default testing framework for Java in Play is JUnit, but you can plug any testing framework in.
The MessageControllerSpec.scala file contains a functional test for the MessageController.
If you modify a test and save the changes, then the tests will automatically be re-run.

SBT Build

SBT is the build system underneath Play applications. It is responsible for resolving dependencies, compiling the project, running the tests, etc. The primary build definition file is the build.sbt file. In that file you will see a comma-seperated list of dependencies which can be modified to suit your needs. Play includes a number of libraries which can selectively be turned on/off. For instance if you want to use JPA with Play, uncomment the javaJpa dependency. You can also add your own dependencies in the SBT form:

"group" % "artifact" % "version"

Typesafe Console

The Typesafe Console visualizes the internals of Play Framework and Akka applications in real-time. To enable the Console you will need a free Typesafe.com account since the Console is licensed under the Typesafe Subscription Agreement which allows it to be used at development time for free. Production use requires a Typesafe Subscription.

To enable the Console, in Run click Login to Typesafe.com and login. If you don't have an account, then sign up and then login inside Activator (click the person icon in the top-right to open the login form). Once logged in, click the Restart with Console button to start the selected application with Console support. There will then be a link to the Console UI. Open that link to enter the Typesafe Console. Learn more about the Typesafe Console.

Further Learning

The Play Documentation contains much more exhaustive details and also covers a number of other topics which haven't been addressed in this tutorial.
StackOverflow is a great place ask questions about Play.
The play-framework Google Group is a great place to discuss Play.

comments powered by Disqus