MySQL / MariaDb + Hibernate XML Configuration Example
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.
Maven Dependencies
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.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.3.Final</version>
</dependency>
Project Structure
Make sure your Book.hbm.xml
and Hibernate.cfg.xml
are on the classpath. In this example we put them in the resources
folder.
src
| +--main
| +--java
| +--com
| +--memorynotfound
| +--hibernate
| |--App.java
| |--Book.java
| |--HibernateUtil.java
| +--resources
| |--Book.hbm.xml
| |--Hibernate.cfg.xml
pom.xml
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.
package com.memorynotfound.hibernate;
import java.io.Serializable;
public class Book implements Serializable {
private Integer id;
private String title;
private String author;
private String isbn;
private Integer year;
private Double price;
public Book() {
}
public Book(String title, String author, String isbn, Integer year, Double price) {
this.title = title;
this.author = author;
this.isbn = isbn;
this.year = year;
this.price = price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbnCode) {
this.isbn = isbnCode;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", author='" + author + '\'' +
", isbnCode='" + isbn + '\'' +
", year=" + year +
", price=" + price +
'}';
}
}
The following 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.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.memorynotfound.hibernate.Book" table="TBL_BOOK">
<id name="id" type="java.lang.Integer" column="ID">
<generator class="identity" />
</id>
<property name="title" column="TITLE"/>
<property name="author" column="AUTHOR"/>
<property name="isbn" column="ISBN" unique="true" length="10"/>
<property name="year" column="YEAR"/>
<property name="price" column="PRICE"/>
</class>
</hibernate-mapping>
Create Hibernate Configuration File
Create the 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 mapping
element.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- database connection properties -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bookstore?serverTimezone=Europe/Brussels</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- show mysql queries output in console -->
<property name="hibernate.show_sql">true</property>
<!-- manage automatic database creation -->
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<!-- add resources here -->
<mapping resource="Book.hbm.xml"/>
</session-factory>
</hibernate-configuration>
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.
package com.memorynotfound.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
}
public static void shutdown() {
sessionFactory.close();
}
}
Create Application
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.
package com.memorynotfound.hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class App {
public static void main (String...args){
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Book book = new Book();
book.setAuthor("Memorynotfound");
book.setTitle("MySQL / Mariadb + Hibernate XML Configuration Example");
book.setIsbnCode("9334537892");
book.setPrice(24.95);
book.setYear(2016);
session.save(book);
tx.commit();
session.close();
HibernateUtil.shutdown();
}
}
Console Output
When you run this application, hibernate logs the following information.
Hibernate: drop table if exists TBL_BOOK
Hibernate: create table TBL_BOOK (ID integer not null auto_increment, TITLE varchar(255), AUTHOR varchar(255), ISBN varchar(10), YEAR integer, PRICE double precision, primary key (ID))
Hibernate: alter table TBL_BOOK add constraint UK_fxrn17ofk6nxyjgheovkirjvh unique (ISBN)
Hibernate: insert into TBL_BOOK (TITLE, AUTHOR, ISBN, YEAR, PRICE) values (?, ?, ?, ?, ?)
Hibernate: drop table if exists TBL_BOOK