This tutorial shows you how to configure MySQL/MariaDB with Hibernate using XML Configuration. We demonstrate this by inserting a POJO into the database. This POJO and database are configured using XML Configuration.
We are using Apache Maven to manage the projects dependencies. Add the following dependencies to your projects
pom.xml file. The database driver
mysql-connector-java is required and works for MySQL and MariaDB databases.
Make sure your
Hibernate.cfg.xml are on the classpath. In this example we put them in the
Create Model Class + Hibernate Mapping File
We demonstrate the hibernate XML configuration by inserting a simple POJO into the database. As you can see, the following POJO has plain java properties.
Book.hbm.xml Hibernate XML Mapping file is located in the
src/main/resources folder and maps/enhances the POJO to the database table. The advantage of using Hibernate XML mapping files is that you don’t ‘clutter’ your Java Classes with meta data.
Create Hibernate Configuration File
hibernate.cfg.xml hibernate configuration file on the classpath in the
src/main/resources folder. In this file, you configure your database properties.
Previously we created the
Book.hbm.xml Hibernate XML mapping file. We can include this file using the
We can optionally configuere hibernate to automatically create the database tables for us. You can do this by adding the hibernate.hbm2ddl.auto property and assign one of the following values: create, create-drop, update or validate.
Manage Sessions with Hibernate Utility
This class configures/initializes hibernate and facilitates the creation of a hibernate session.
Now that all ingredients are in place, we can demonstrate this example by inserting a record in the database.
- Obtain the Hibernate Session.
- Start a new Transaction.
- Create and Save the Book POJO.
- Commit the Transaction.
- Close the Hibernate Session.
When you run this application, hibernate logs the following information.