Simon
Simon

Reputation: 188

How to add cache mechanism when using anorm in Playframework

I see anorm is not a ORM framework, it is querying data directly by SQL. For most of the application/website, we should not query the database everytime, we needs to cache the data either by SQL or item id. I wonder whether playframework has provided any kind of caching mechanism? If not how to add it?

Thanks.

Upvotes: 5

Views: 2125

Answers (3)

Pere Villega
Pere Villega

Reputation: 16439

You can simply cache the answer of the Anorm methods. For example, real method that I use:

def findById(id: Long): Option[User] = {
    Cache.getOrElse(userCacheKey + id, 60*60) {
      DB.withConnection {
        implicit connection =>
          SQL("select * from publisher where id = {id}").on('id -> id).as(User.simple.singleOpt)
      }
    }
}

The code does the Select and stores the answer in the cache via getOrElse. If the value is in the Cache, it will ber etrieved and no query will be executed.

The only issue is that when you update the entity User you'll have to update the cache (so it doesn't keep stale data):

// Assumes a user: User object available with the updated user
Cache.set(userCacheKey + id, cached.copy(name = user.name, avatar = user.avatar, bio = user.bio, url = user.url, location = user.location), 60*60)

Upvotes: 7

ndeverge
ndeverge

Reputation: 21564

You can use the Play cache in your controller, before querying your database. Here is a straightforward example derived from the Play cache documentation and the Scala API:

val user: User = Cache.getOrElse[User](key = "user" + userId, expiration = 10) {
  User.findById(userId)
}

In this code, before trying to query the database, we make a lookup in the cache to check if the User has not been loaded previously. If not found in the cache, we store it in the cache with an expiration in 10 seconds.

Upvotes: 11

Arg
Arg

Reputation: 1916

Assuming you are using Play2 framework, it indeed does provide a cache mechanism. It has nice documentation here:

http://www.playframework.org/documentation/2.0/JavaCache (its called javacache, but it works from Scala)

Upvotes: 0

Related Questions