Managing many MSSQL connections

(Salux X) #1

Hi there, I’m upgrading from 2.4.4 to 2.6.21 and have an issue with my projects DB connections to MSSQL DBs

Previously I just extracted datasource from DB class and fed it to the java.sql for handling, with update 2.5 it became different and example says I should create a class for each DB (is there a way to create new connections without creating a class that injects it?..). I want to execute simple queries that have no model binding to DB and their task is to extract simple data sets from many large DBs. What’s the best way to approach it?

How to receive db connection in controller? Seems it shouldn’t done anymore? should I move all DB interaction into new DB class and inject it into controller? What if I need to access DB not from controller? Play doesn’t inject classes natively to classes that are not controllers (in my experience, and I’ve been used deprecated Play.application().injector().instanceOf(Configuration.class))

Is there a way to access simple data structure from a view? Previously I used static access to DB to query simple values into temple. It’s not clean ye, but worked as I’ve a LOT of those and passing them via controller would require so much parameters. Is there no other way?

So many questions, so little documentation =(

(Marcos Pereira) #2

Hi @salux-x,

You don’t need to create a class for each database. Can you point where the documentation is saying that? What is happen is that when you need to access a DataSource, you then inject it by using the name of the database you configured before or no @NamedDatabase annotation if you want the default one.

After that, you can use play.db.Database withConnection methods to execute whatever you want.

db.withConnection(connection -> {
    // do whatever you need with the db connection
    return 1;

So, for your controllers, you can inject Database as the documentation examples show:

public class FooController extends Controller {

    private final play.db.Database database;

    private FooController(play.db.Database database) {
        this.database = database;

    public Result action() {
        return db.withConnection(connection -> {
            // do what you need to do and return a Result

This is incorrect. See the examples in the docs linked above.

Query your database inside the templates is an anti-pattern. Play is a MVC framework, so it favors this way of doing things. Of course, you can push hard enough and do queries directly inside your views, but this is simply not documented because we don’t recommend it.

Model things as objects. Instead of having a single parameter name, another one age, and another address, try to create a Person class that encapsulates that.


(Salux X) #3

Thanks! Figured it out!
Very helpful.