22 March, 2017
Setting Up Play Framework Evolutions with Dependency Injection and MySQL
If you’re anything like us, you love Scala and Play Framework. You are probably a fierce advocate of compile time dependency injection (who wants to have to actually run their app to know if it’s correct?). You definitely have a database and want to use Play Framework’s evolutions for database migrations. However, if you read Play’s documentation, you’ll find that it’s a little incomplete and you need to do a little detective work through the Scaladocs to piece things together. We did that digging when we set up our MySQL databases with Play, and have compiled our findings here so you don’t have to waste time searching. This guide expects working knowledge of compile time DI in Play.
First, you’ll need to add the correct dependencies to your project definition’s settings in SBT.
Next, you’ll want to set up the class that extends play.api.BuiltInComponentsFromContext. It will need to mix in some components that give you access to the database and the Evolutions system.
Play’s documentation mentions EvolutionsComponents, but you’ll also need DBComponents to provide the dbApi that EvolutionsComponents needs, and mixing in HikariCPComponents will let you use Play’s default connection pooling. You’ll also have to get an instance of play.api.db.Database to pass to your models so you can get database connections.
That’s it! Now that you’ve provided a Database object to your model, you can query your databases just like the examples in Play’s documentation!
Looking to reduce downtime?
Sign up for the Blue Matador platform beta and get access to 30 days of AI-powered centralized log management with Lumberjack and forever-free smart alerts with Watchdog.