Documentation / Setup / DatabaseBuilder
Overview
The preferred way to programmatically configure Ebean is via Database.builder()
and DatabaseBuilder.
This keeps database creation explicit, works naturally with dependency injection,
and avoids relying on implicit bootstrap through the DB singleton.
For new applications, prefer injecting Database and calling methods on
that instance directly.
Database.builder()
Build the Database explicitly and keep the instance returned from
build().
var dataSource = DataSourceBuilder.create()
.username("my_app")
.password("secret")
.url("jdbc:postgresql://localhost:5432/my_app");
Database database = Database.builder()
.name("db")
.dataSourceBuilder(dataSource)
.build();
Load from properties
If some configuration lives in application.yaml or application.properties,
load it explicitly with the builder rather than relying on automatic bootstrap.
Database database = Database.builder()
.name("pg")
.loadFromProperties()
.build();
For named databases, set the name before loadFromProperties() so the
matching datasource configuration is loaded.
Register
By default a built Database is registered with the DB registry,
and that is generally the right choice. Query beans, Model and other default-database-based
APIs resolve the database through that registry under the hood.
Only disable registration for isolated or one-off databases that are never referenced that way.
Database database = Database.builder()
.name("reporting")
.loadFromProperties()
.register(false)
.defaultDatabase(false)
.build();
Default database
One registered Database is typically left as the default database. Query beans,
Model and older convenience APIs commonly resolve against that default registration.
Even so, for new code prefer using the injected Database directly rather than
calling DB convenience methods in application code.
Database database = Database.builder()
.name("db")
.loadFromProperties()
.defaultDatabase(true)
.build();
Dependency injection
With Guice, Spring, Avaje Inject and similar DI frameworks, create the
Database in a provider or bean factory and inject the resulting
instance where needed.
@Bean
Database database() {
return Database.builder()
.name("db")
.loadFromProperties()
.build();
}
Older versions referred to ServerConfig / EbeanServerFactory.
If you are migrating older setup code, see docs / upgrading.