How to use multiple neo4j databases in Spring Boot?

85 views Asked by At

I am trying to configure my Spring Boot application to use multiple neo4j databases. I could not find any example of it on the web and thought I should ask.

Should we define the settings in the .properties for each database? Should we define a Driver bean for each in the config class? How should we know which Neo4jTemplate is used?

Edit: I have 2 different settings in my .properties

###Neo4j db1
spring.neo4j.db1.uri=bolt://localhost:17486
spring.neo4j.db1.authentication.username=neo4j
spring.neo4j.db1.authentication.password=pass
spring.data.neo4j.db1.database=db1

##Neo4j db2
spring.neo4j.db2.uri=bolt://localhost:17486
spring.neo4j.db2.authentication.username=neo4j
spring.neo4j.db2.authentication.password=pass
spring.data.neo4j.db2.database=db2

I have the corresponding Configuration classes. I am not going to have them both here but the missing one almost identical except for the meaningful Qualifier names.

@Configuration
@EnableNeo4jRepositories(basePackages = "com.horsefly.companymodel.repository.db1")
@EnableTransactionManagement
public class Neo4jDB1 {

    @Value("${spring.neo4j.db1.uri}")
    private String uri;

    @Value("${spring.neo4j.db1.authentication.username}")
    private String username;

    @Value("${spring.neo4j.db1.authentication.password}")
    private String password;

    @Value("${spring.data.neo4j.db1.database}")
    private String databaseName;

    @Bean(name = "db1Driver") //same for db2
    public Driver db1Driver() {
        return GraphDatabase.driver(uri, AuthTokens.basic(username, password));
    }

    @Bean(name = "db1TransactionManager") //same for db2
    public Neo4jTransactionManager neo4jTransactionManager() {
        return new Neo4jTransactionManager(db1Driver());
    }

    @Bean(name = "neo4jClientdb1")// same for db2
    public Neo4jClient neo4jClientdb1() {
        DatabaseSelectionProvider databaseSelectionProvider = () -> DatabaseSelection.byName("db1"); //entered manually.
        return Neo4jClient.create(db1Driver(), databaseSelectionProvider);
    }

    @Bean(name="neo4jTemplatedb1") // same for db2
    public Neo4jTemplate neo4jTemplate(@Qualifier("neo4jClientdb1") Neo4jClient client, Neo4jMappingContext neo4jMappingContext) {
        return new Neo4jTemplate(client, neo4jMappingContext);
    }
}

When I ran the app, I saw the below, although I have qualifiers to distinguish them

required a bean named 'neo4jTemplate' that could not be found.
Action:Consider defining a bean named 'neo4jTemplate' in your configuration.
0

There are 0 answers