Working with Play framework using Scala and MongoDB


Scala : Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. More…

Play Framework : Play 2.0 is a high-productivity Scala web application framework that integrates the components and APIs you need for modern web application development.

Play is based on a lightweight, stateless, web-friendly architecture. More…

MongoDB : MongoDB is a scalable, high-performance, open source NoSQL database. More…
Here we’ll have a look to use all these three together with help of small code snippets.
Creating a Play Scala Project using new command like :

play new Play_Scala_MongoDB_Tutorial

Adding Dependecies :

Add the following dependencies in ‘Build.scala’ File in order to use MongoDB (Here we’ll be using SalatDAO).

 "com.mongodb.casbah" %% "casbah" % "2.1.5-1",
 "com.novus" %% "salat-core" % "0.0.8-20120223",
 "commons-codec" % "commons-codec" % "1.6"

Preparing Requests (GET and POST) : Here we are taking an example of a simple GET request.

You can define the requests path and the correspondent methods in “routes” file like :

GET     /callMe                    controllers.Tutorial.testMethodForPlayTutorial

Here we are defining that a GET request on this URL ” /callMe” would hit the method testMethodForPlayTutorail in Tutorial Controller.

Writing Controller : Now we are going to write Tutorial controller under “app/controllers”.

package controllers
import play.api.mvc.Controller
import play.api.mvc.Action

object Tutorial extends Controller {

  def testMethodForPlayTutorial = Action { implicit request =>
    Ok("Method Hit is here")
  }

}

Now you can run your application using following command & you’ll find your output at http://localhost:9000/callMe

/Play_Scala_MongoDB_Tutorial$ play run     //running the project

Connecting to MongoDB :

You’d require mongoDB running locally. We’ll use SalatDAO framwork to store the Data in mongoDB.You’d get an idea from this example of how to interact with MongoDB.

Firstly let us create the MongoDB connection class

Connection Class

package models
import com.mongodb.casbah.MongoConnection

object MongoDBSetup {
  val mongoDB = MongoConnection()("test_database")
}

Saving data in MongoDB :

Model Class

package models
import com.novus.salat.dao.SalatDAO
import org.bson.types.ObjectId
import models.MongoDBSetup
import com.novus.salat.global._

case class SaveData(username: String,
  Marks: Int,
  email: String)                                 // SaveData Model

object SaveData {

  def saveTheDataInMongo {
    val dataToSave = new SaveData("Neelkanth", 87, "neelkanth@knoldus.com")
    SaveDataDAO.insert(dataToSave)
  }

}

object SaveDataDAO extends SalatDAO[SaveData, ObjectId](collection = MongoDBSetup.mongoDB("saved_data"))

Now recall & modify the testMethodForPlayTutorial method.

def testMethodForPlayTutorial = Action { implicit request =>
    SaveData.saveTheDataInMongo                    //calling the method
    Ok("Stored data in database")
  }

Now on hitting the URL http://localhost:9000/callMe would generate the GET request that will create a database test_database and stores the data in collection saved_data.

GitHub Repo for this example.
:-)

About these ads

About Neelkanth Sachdeva

Software Consultant @ Knoldus Software LLP Co-Founder @ My Cell Was Stolen
This entry was posted in Java, Scala, Web and tagged , , . Bookmark the permalink.

4 Responses to Working with Play framework using Scala and MongoDB

  1. Nice stuff.

    Leon Radley has created a plugin for using salat with play2 [1] for an example on how this is used see [2].

    [1] https://github.com/leon/play-salat
    [2] https://github.com/bjartek/computer-database-mongo

    I am working on doing the computer-database-mongo example in java aswell and will send a pull request to Play when it is done. So there will be a mongo sample in Play this fall hopefully.

    regards
    Bjarte

  2. nicowernli says:

    Any tutorials on how to use mongodb with playframework 2 and Java?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s