skip to Main Content

(help to create multiple databases in spring boot in my answer)

I want to make a spring boot application for different games. The data of each game is placed in a separate database. I have been trying to connect a secondary database to my existing application, but the controller/repository keeps using the primary database.

This is what the controller for the second database looks like:

@RestController
@RequestMapping("/valorant")
@CrossOrigin
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    @Qualifier("valorantDataSource")
    private DataSource valorantDataSource;

    @GetMapping("/users")
    public Iterable<User> getUsers() {
        return userRepository.findAll();
    }
}

This is the repository that should take the data from the second database:

@Repository
@Qualifier("valorantDataSource")
public interface UserRepository extends JpaRepository<User, Long> {
}

I have defined the datasources in a different file. (Adding .url(), .username() and .password() to the datasourcebuilder did not help)

@Configuration
public class DatasourceConfig {

    @Primary
    @Bean(name = "apexDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "valorantDataSource")
    @ConfigurationProperties(prefix = "spring.second-datasource")
    public DataSource valorantDataSource() {
        return DataSourceBuilder.create()
                .build();
    }
}
# First database
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/apex
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Second database
spring.second-datasource.jdbc-url=jdbc:mysql://localhost:3306/valorant
spring.second-datasource.username=root
spring.second-datasource.password=
spring.second-datasource.driver-class-name=com.mysql.cj.jdbc.Driver

When I used postman to go to http://localhost:8080/valorant/users, i got the error:

java.sql.SQLSyntaxErrorException: Table ‘apex.user’ doesn’t exist

So it seems like the application is trying to look in the wrong database.

enter image description here

Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    I ended up using an existing project. I cloned this repo, changed some names and values and it was ready to use in my own project.


  2. You should not use @Primary annotation in this case.

    When you mark bean with @Primary, it will be selected for dependency injection
    Marking your beans with @Qualifier would be enough to select concrete bean.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search