In the Drivine neo4j driver, how do I set the application to connect to a specified database in code without setting the environment variables.
Asked
Active
Viewed 138 times
1 Answers
2
To register a new connection dynamically:
Ensure that the following code has been called first:
DatabaseRegistry.getInstance().builder()
.withType(DatabaseType.NEO4J)
.host(host)
.userName(userName)
.password(password)
.databaseName(dbName) // On Neo4j version 4 we can have multiple DBs
.port(nonStandardPortIfNeeded)
.register('MY_UNIQUE_NAME');
Note: Rather than using the DatabaseRegistry
as a singleton, you can of course also @Inject()
it.
The code above could go in the body of the constructor below, or anywhere, as long as it is called before the persistence manager is obtained from the factory.
Obtain Persistence Manager From Factory:
Once a database has been registered, you can obtain a persistence manager for that db, like this:
@Injectable()
export class PersonRepository {
readonly persistenceManager: PersistenceManager;
constructor(@Inject() readonly factory: PersistenceManagerFactory) {
}
async someOperation(): Promise<void> {
const persistenceManager = this.factory.get('MY_UNIQUE_NAME')
//Now use persistence manager
}
}
Details:
- In the first case we use the
DatabaseRegistry
's builder to build or resolve a namedConnectionProvider
with the specified properties. - In the second case we use the
PersistenceManagerFactory
to obtain aPersistenceManager
for the named connection details. The connection provider takes care of returning a connection (possibly pooled depending on platform) for that database in the most expedient manner.
And that's it. By the way, Drivine works for other graph databases as well.

Jasper Blues
- 28,258
- 22
- 102
- 185
-
To clarify .`databaseName(dbName)` is the url of the database, correct? – Peter Clemenko Jun 30 '20 at 04:13
-
https://adamcowley.co.uk/neo4j/multi-tenancy-neo4j-4.0/. <-- Neo4j v4 supports multiple databases in once server. If you have created additional databases, as per Adam's guide, then we can use them in Drivine by specifying the name. With no name, it will use the default v1,2 and 3.x compatible DB. – Jasper Blues Jun 30 '20 at 05:54
-
So if you have created a database called 'customers' you put the string 'customers'. Not the URL, just the string name. – Jasper Blues Jun 30 '20 at 05:57
-
So wait, where does the database address/url go then? – Peter Clemenko Jun 30 '20 at 09:09
-
OK, looked at the database api docs. The example is missing .host https://drivine.org/api/classes/_src_connection_connectionproviderbuilder_.connectionproviderbuilder.html – Peter Clemenko Jun 30 '20 at 09:26
-
Oops, sorry @AoiGhost!!. Have added it now. – Jasper Blues Jun 30 '20 at 12:39