It is important to understand that the usual flow of a production application is not to open and close connections several times, as that is an expensive / slow operation.
Ideally, you would use some form of connection pooling - you keep some connections to the server open, and when you need to perform a query you pick one of the connections that is idle, perform the query, and return the connection to the pool. If no connections are idle, usually you can set a configuration to either wait for one to be idle or to open a new one (that will belong to the pool once it becomes idle).
There are several libraries that can perform connection pooling for you on Java; a quick search returned this result https://www.baeldung.com/java-connection-pooling