Chapter 5. Working with Data

The MVC approach talks about the model, view, and controller. We have seen views and controllers in detail in the previous chapters and neglected models to quite an extent. Models are an important part of MVC; the changes made to a model are reflected in the views and controllers using them.

Web applications are incomplete without data transactions. This chapter is about designing models and handling DB transactions in Play.

In this chapter, we will cover the following topics:

  • Models
  • JDBC
  • Anorm
  • Slick
  • ReactiveMongo
  • A Cache API

Introducing models

A model is a domain object, which maps to database entities. For example, a social networking application has users. The users can register, update their profile, add friends, post links, and so on. Here, the user is a domain object and each user will have corresponding entries in the database. Therefore, we could define a user model in the following way:

case class User(id: Long,
                loginId: String,
                name: Option[String],
                dob: Option[Long])
object User { def register (loginId: String,...) = {…}
...
}

Earlier, we defined a model without using a database:

case class Task(id: Int, name: String)

object Task {

  private var taskList: List[Task] = List()

  def all: List[Task] = {
    taskList
  }

  def add(taskName: String) = {
    val lastId: Int = if (!taskList.isEmpty) taskList.last.id else 0
    taskList = taskList ++ List(Task(lastId + 1, taskName))
  }

  def delete(taskId: Int) = {
    taskList = taskList.filterNot(task => task.id == taskId)
  }
}  

The task list example had a Task model but it was not bound to a database, keeping things simpler. At the end of this chapter, we will be able to back it up with a database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.128