Play 2.6.9 - What should I use in place of the deprecated play.db.DB?


(koz) #1

In the docs it says to use play.api.Database, but this class does not exist. Could it be play.db.DefaultDatabase instead?


(Marcos Pereira) #2

Hi @koz,

Which docs? If it is a Java project, that you need to follow the instructions here:

https://www.playframework.com/documentation/2.6.x/JavaDatabase

If it is a Scala project:

https://www.playframework.com/documentation/2.6.x/ScalaDatabase

Notice that you need to add the proper dependencies.

I’m asking because play.api.Database is from the Scala API (if there is an api, then it is the Scala API) and you later referenced play.db.DefaultDatabase which is from the Java API. Anyway, the docs should be a good start point.

Best.


(koz) #3

Hello Marcos thank you for your reply. It’s a Java project.

I’m asking because I have to implement multitenancy with Hibernate, and so I have to implement the MultiTenantConnectionProvider interface, and in the method “getAnyConnection()” I have to return a database connection, but I don’t know from where I’m supposed to get this connection.

I tried this, but I’m getting a null pointer in the “db.getConnection();”


import play.db.Database;

public class MultiTenantConnectionProviderImplementation implements MultiTenantConnectionProvider, ServiceRegistryAwareService {

	@Inject
	private Database db;

	@Override
	public Connection getAnyConnection() throws SQLException {
		return db.getConnection();
	}

(Marcos Pereira) #4

Hi @koz,

Use this instead:

public class MultiTenantConnectionProviderImplementation implements MultiTenantConnectionProvider, ServiceRegistryAwareService {

    private final Database db;

    @Inject
    public MultiTenantConnectionProviderImplementation(Database db) {
        this.db = db;
    }

    @Override
    public Connection getAnyConnection() throws SQLException {
        return db.getConnection();
    }
}

I’m not sure Guice is able to inject private fields, but by declaring a constructor, you make it more explicit that MultiTenantConnectionProviderImplementation depends on Database, including in your tests or when manually creating instances of your class. It is also a recommended best practice.

Best.