Clayton, you’re missing some concepts about how hibernate works. There are actually several sources that teach differently and I understand that this makes it very confusing for those who are starting out. But, precisely for this reason, try to read some more reliable book or source on the subject to understand the concepts and then be able to judge for yourself what is the best way to solve your problem.
Persistence.xml
The first important point for you to understand is about the persistence.xml
.
Here you can configure connection data and the classes (entities) that map database tables.
This is a configuration file and does not directly concern how many connections or tables you have in the database.
Anyway, you don’t have to worry too much about this file in that sense.
Connections
Hibernate or any other JPA implementation will not open a connection for each table or entity, nor will it necessarily open a connection every time you read or write something from the bank. One has nothing to do with the other.
If your application is Swing, you will probably just want a single open connection to the database and reuse it whenever necessary.
If it were a web application, you could have a pool connections to optimize application performance.
EntityManagerFactory
and EntityManager
To use Hibernate with the JPA API you will use the classes EntityManagerFactory
and EntityManager
.
EntityManagerFactory
The EntityManagerFactory
is who will load the settings from persistence.xml
. Creating an instance of this class is costly and slow, as Hibernate will initialize several things and can read and change the database, depending on its configuration.
The recommendation is to create the EntityManagerFactory
once per database and then reuse it to create the EntityManager
whenever it is necessary to access the database.
EntityManager
The EntityManager
is roughly the equivalent of a database connection. With it you will perform the necessary operations with JPA in the database.
In an application desktop you can create only one instance of EntityManager
and reuse whenever necessary, as long as there is no competition thread-safe. In the case of several threads it would be advisable to create a EntityManager
for each of them.
Considerations
I hope I was able to give a brief introduction to the subject.
And finally, I suggest you use a framework like Spring to manage its "components" (classes), the connection to the database and the injection of dependency on the EntityManager
.
Even in applications that run locally, a framework can help you not reinvent the wheel and end up with more problems due to lack of experience.
I did a brief research and found an open project with the technologies mentioned. It can serve as a basis for you. To access it, click here.