You could use the getOrElse
method like this:
Cache.getOrElse[Option[Learner]]("learner." + id, expiration_time) {
DB.withConnection { implicit c => //-- no cache, read DB
SQL("select * from learner where id={id}")
.on('id -> id)
.as(learnerP.singleOpt)
}
}
If the Option[Learner]
is found in memory, it is returned immediately, if it isn't, the call to DB is done and the result is cached with an expiration time expiration_time
.