My question is, I really need to open and close the connection to every controller call?
Database connections are usually stateless. I mean, open up, do what you gotta do and close up.
I particularly see no reason to hold an open connection with the bank, even because there are datasource settings which precisely check whether there are idle connections and close them.
When I say "do what you have to do" it does not mean executing a single query. You can execute N queries, N transactions and etc.
If you have a customer list to register at the bank, for example, you do not need to open and close a connection for each item on that list. You can very well open a connection, iterate the list by entering all customers in the bank through that connection and then close it. The important thing is not to hold the connection open "forever".
The way I use it today won’t bring me performance problems?
If you use Pool of Connections no. The pool is designed precisely for the purpose of facilitating/making it less costly to redeem a bank connection.
I have the same doubt, but beyond the performance I would still ask about the safety of keeping an open connection throughout the application’s lifetime.
– Hamurabi Araujo
You don’t have to, as long as you use the Try-with-Resources, because it closes for you. Now if you want to reuse, the interesting is to work with connections pool.
– user28595
@diegofm would still not be opening and closing the connection?
– Lucas Martins
would not be, because the connection pool tells the application that closed the connection but keeps it inside the pool to be reused. This is the magic of the connection pool to reuse them for better performance.
– Flávio Granato
Yes, in case, the pool would be even the best solution. Thank you :)
– Lucas Martins