The following screenshot depicts the main participants in the Hibernate architecture:
As the screenshot shows, the main players are Hibernate configuration file(s), mapping definitions, and persistent objects. At the heart of Hibernate is its configuration. This configuration is always presented by an XML, or a properties file and includes the relevant database information, such as database username, password, URL, driver class, and SQL dialect that Hibernate needs for connecting to the database, communicating with it, and performing persistence operations.
Persistent objects form another part of the Hibernate architecture. These objects are what we will persist in the database. These entity objects and their classes, as upcoming chapters explain, do not need to exhibit any special behavior, except that they must follow some POJO rules.
In addition to the Hibernate configuration file and the persistent objects, Hibernate's architecture uses other XML documents, which define how application objects should be mapped to database tables. These documents specify the respective table of each entity class, the mapping of each class's field to its respective table column, and sometimes other mapping information, such as object associations and inheritance. These files have a simple syntax, making them easy to develop and maintain. However, some utility tools that ship with Hibernate let you automatically generate the mapping files, based on the application classes or database schema, and also allow you to modify them in a graphic tool.
Although these objects are the main players in the Hibernate architecture, a Hibernate application's runtime architecture is not limited to them. As we will see in the chapters that follow, the most significant runtime objects are Configuration
, SessionFactory
, Session
, and Transaction
.
Hibernate can be used as simply as follows to store or retrieve a Student
object:
Configuraion cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Student student = …//a new instantiated student object
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(student);
tx.commit();
session.close();
Here, we have just configured Hibernate, started a transaction, stored the student object, committed the transaction, and finally disconnected from Hibernate. These are actually the required operations to interact with Hibernate. The configuration includes setting up Hibernate to work with a particular database with special behavior. Every Hibernate interaction should be done inside a transaction, which justifies the next step. Don't worry, all of these concepts with their usages will be explained in the future chapters.