Playframework with anorm and Spring DataSource

230 views Asked by At

Problem:

Is there a way to use the anorm mapper with a 'user provided' DataSource?

Long story:

I want to use Spring Cloud to configure the DataSource for my Play application. I am struggling with this issue for a while now and have tried a lot bot nothing has worked so far.

I need to do this, because the auto configuration for the cloud we are using (CloudFoundry) is not working properly (see bug report).

After setting up the Spring Cloud for my application, I get a DataSource that should be used by anorm. But there is no way to inject this DataSource into Anorm. The Play Anorm plugin only works with the Play DBPlugin that is hardcoded to use the default database from the application.conf (db.default) or at least one of the databases that can be read from the confiugration file.

I found an older blog post that showed a method to set the DataSource used by the DBPlugin. But setting

DB.datasource = dataSource;

isn't allowed for the Play version I am currently using.

1

There are 1 answers

1
James Roper On BEST ANSWER

Anorm knows nothing about what datasource you are using. Every method on anorm that talks to the database takes an implicit java.sql.Connection parameter. It's up to you to decide where that connection comes from. Obviously the most common way is to use Play's DB API, using DB.withConnection or DB.withTransaction, but you could write your own that uses your own datasource.

It's also possible to write a custom DB plugin and disable the default Play one which is based on bonecp, if you do this then you can use the Play DB API with your custom datasource. To do this, implement your own play.api.db.DBApi and play.api.db.DBPlugin implementations, create a play.plugins file that has your db plugin registered (eg, with 100:com.foo.MyDbPlugin in it), and then disable Play's built in one by adding dbplugin=disabled in application.conf.