Chapter 5. Storing data—the persistence layer

 

This chapter covers

  • Using Anorm
  • Using Squeryl
  • Caching data

The persistence layer is a crucial part of the architecture for most Play applications; unless you’re writing a trivial web application, you’ll need to store and retrieve data at some point. This chapter explains how to build a persistence layer for your application.

There are different kinds of database paradigms in active use, today. In this chapter we’ll focus on SQL databases. Figure 5.1 shows the persistence layer’s relationship to the rest of the framework.

Figure 5.1. An overview of Play’s persistence layer

If we manage to create our own persistence layer without leaking any of the web application concepts into it, we’ll have a self-contained model that will be easier to maintain, and a standalone API that could potentially be used in another application that uses the same model.

In this chapter we’ll teach you how to use Anorm, which comes out of the box with Play and Squeryl.

5.1. Talking to a database

In order to talk to the database, you’ll have to create SQL at some point. A modern object-relation mapper (ORM) like Hibernate or the Java Persistence API (JPA) provides its own query language (HQL and JPQL, respectively), which is then translated into the target database’s SQL dialect.

5.1.1. What are Anorm and Squeryl?

5.2. Creating the schema

5.3. Using Anorm

5.4. Using Squeryl

5.5. Caching data

5.6. Summary