MySQL / MariaDb + Hibernate Annotation Configuration Example

Ap>This tutorial shows you how to configure MySQL/MariaDB with Hibernate using Annotation Configuration. We demonstrate this by inserting a POJO into the database. This POJO is enhanced with standard Java persistence annotations, which makes the code portable.

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.


Project Structure

Make sure the Hibernate.cfg.xml resides on the classpath in the src/main/resources folder.

|    +--main
|        +--java
|            +--com
|                +--memorynotfound
|                    +--hibernate
|                        |
|                        |
|                        |
|        +--resources
|            |--Hibernate.cfg.xml

Model Class + Hibernate Annotations

We demonstrate the hibernate Annotation configuration by inserting a simple POJO into the database. As you can see, the following POJO has plain java properties. The properties are enhanced with java persistence annotations.

package com.memorynotfound.hibernate;

import javax.persistence.*;

@Table(name = "TBL_BOOK")
public class Book implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Integer id;
    @Column(name = "TITLE")
    private String title;
    @Column(name = "AUTHOR")
    private String author;
    @Column(name = "ISBN", length = 10, unique = true)
    private String isbn;
    @Column(name = "YEAR")
    private Integer year;
    @Column(name = "PRICE")
    private Double price;

    public Book() {

    public Book(String title, String author, String isbn, Integer year, Double price) {
        this.title = title; = author;
        this.isbn = isbn;
        this.year = year;
        this.price = price;

    public Integer getId() {
        return id;

    public void setId(Integer 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) { = author;

    public String getIsbn() {
        return isbn;

    public void setIsbn(String isbn) {
        this.isbn = isbn;

    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;

    public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", isbn='" + isbn + '\'' +
                ", year=" + year +
                ", price=" + price +

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.

We can include the POJO using the mapping element and provide the class.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        <!-- 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="">create-drop</property>

        <!-- add resources here -->
        <mapping class="com.memorynotfound.hibernate.Book"/>

We can optionally configuere hibernate to automatically create the database tables for us. You can do this by adding the 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() {

Create Application

Now that all ingredients are in place, we can demonstrate this example by inserting a record in the database.

  1. Obtain the Hibernate Session.
  2. Start a new Transaction.
  3. Create and Save the Book POJO.
  4. Commit the Transaction.
  5. 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.setTitle("MySQL / Mariadb + Hibernate Annotation Configuration Example");


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



You may also like...