user2482989
user2482989

Reputation: 45

Spring Data when does it connect to the database

I have been researching Spring Data Rest especially for cassandra and one of the questions my coworkers and I had was when does Spring Data connect to the database. We don't always want a rest controller to connect to the database so when does spring establish a connection if say we had a class extend the CRUDRepository? Does it connect to the database during the start of application itself? Is that something we can control?

For example, I implemented this example on Spring's website: https://spring.io/guides/gs/accessing-data-rest/

At what point in the code does spring connect to the database?

Upvotes: 3

Views: 2365

Answers (2)

Rahul Kumar
Rahul Kumar

Reputation: 114

Disagree with the above answer. As part of research i initiated the datasource using a bean configuration and then changed my database password(not in my spring application but the real db username password) The connection stays for a while and then in some point of time (maybe idle time) it stops working and throws credential exception. This is enough to say the JPA does not keep the connection sitting and waiting to be used but uses some mechanism to occupy/release the db connection as per the need.

Upvotes: -1

Desorder
Desorder

Reputation: 1539

Spring will connect to the DB as soon as the Datasource get initialized. Basically, Spring contexts will become alive somehow (Web listeners, manually calling them) and start creating beans. As soon as it reaches the Datasource, connection will be made and the connection pool will be populated.

Of course the above is based on a normal out of the box configuration and everything can be setup up to your taste.

So unless, you decide to control the connections yourself, DB connections will be sitting there waiting to be used.

Upvotes: 4

Related Questions