Clayton, you're missing some concepts about how Hibernate works. There are actually several sources that teach different and understand that this makes the thing very confusing for those who are starting. But just so, try to read some more reliable book or source on the subject to understand the concepts and then be able to judge for yourself how best to solve your problem.
Persistence.xml
The first important point for you to understand is about persistence.xml
.
In it you can configure connection data and 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 do not have to worry about this file too much.
Connections
Hibernate or any other JPA implementation will not open a connection to each table or entity, nor will it necessarily open a connection every time you read or write something from the database. One thing has nothing to do with the other.
If your application is Swing, you probably want only a single open connection to the database and reuse it whenever necessary.
If it was a web application, you could have a pool of connections to optimize application performance.
EntityManagerFactory
and EntityManager
To use Hibernate with the JPA API you will use the EntityManagerFactory
and EntityManager
classes.
EntityManagerFactory
The EntityManagerFactory
is who will load the persistence.xml
settings. Creating an instance of this class is costly and time-consuming since Hibernate will initialize a number of things and can make readings and changes to the database, depending on its configuration.
The recommendation is to create EntityManagerFactory
once per database and then reuse it to create EntityManager
whenever you need to access the database.
EntityManager
The EntityManager
is more or less the equivalent of a database connection. With it you will perform the necessary operations with JPA in the database.
In a desktop application you can only create an instance of EntityManager
and reuse it whenever necessary, as long as there is no concurrency because it is not thread-safe . In the case of multiple threads it would be advisable to create a EntityManager
for each of them.
Considerations
I hope I have been able to give you a brief introduction.
And to conclude, I suggest you use a framework like Spring to manage your "components" (classes), the connection to the database and dependency injection of EntityManager
.
Even in applications that run locally, a framework can help you not reinvent the wheel and end up with more problems for lack of experience.
I did a brief survey and found an open project with the technologies mentioned. It can serve as the basis for you. To see it through, click here .