Ladies and Gentlemen! We have finally hit a milestone in our journey of learning Java, we are now done talking specifically about SQL and are moving on to talk about persistence frameworks.

Let's start with the most obvious question first…

What is a Persistence Framework?

As the name implies, it has something to do with persisting things… this means that we're still talking about databases. But what is it that we are persisting with this framework?

Objects (of course)

A persistence framework is something we use in Java to bridge the gap between Java and SQL.

Hopefully we've gone through all of my previous tutorials and have learned a thing or two about Java and SQL. But one thing I haven't taught you yet, is how to put your knowledge of SQL into Java.

That's what I'll be teaching you throughout these Hibernate (persistence framework) tutorials.

And if you haven't guessed it already, Hibernate is a persistence framework that you can use in Java. It's what allows you to write Java code (staying true to Object Oriented programming practices) and yet still be able to communicate with your database. Cool eh?

Why use Hibernate?

Overall, Hibernate is widely adopted and is open source software. This means that you'll have very readily accessible help documentation across the internet (just like the one you're reading right now). The more users a particular project/framework has, the more overall support you'll be able to receive.

Hibernate is no exception to this rule, there are hundreds (if not thousands) of blogs dedicated to Hibernate and Hibernate tutorials.

Not only that, Hibernate is a fairly simple and flexible framework to use when compared to other alternatives out there. You'll be able to use Hibernate with pretty much any database system you plan on using (including the big ones like MySQL, MS SQL Server, Oracle, PostgreSQL).

Hibernate also integrates and plays nice with the Spring Framework. which is another framework that you're hopefully already familiar with. If you're not, then I'd suggest reading up on it.

What you need to know when using Hibernate

There are some pre-requisites for learning Hibernate. I'm going to be progressing through these Hibernate tutorials assuming that you already have at least a beginners grasp on the following languages / technologies:

  1. Java
  2. Spring Framework
  3. SQL

If you don't already understand the things listed above, then you're going to have to pause your learning on Hibernate, because you'll likely get lost in all the details.

If you have a good understanding of those concepts / technologies, then you're almost good to go. We'll need to talk a little bit about a technology called Maven before we can continue.

You see, Maven was created by Apache with the goal of simplifying the annoying project management aspect of programming (namely the build process and library management). As a software project grows, you're more likely to need to depend on 3rd party software / library (like Spring and Hibernate) to get the job done right.

Getting Spring and Hibernate set up correctly and running is actually a VERY annoying and somewhat complex task… especially since there are so many bloody versions of each framework. This is where Maven comes in, it allows you to MUCH more easily point to the version of each framework that you want to use and then “install it”.

Maven uses something called a “project object model” to manage your projects… this is just a fancy way of saying, they have a single XML file where you will specify all the information about what frameworks you'd like your project to use. It's not too difficult to use once you get used to it.

The goal of these tutorials, however, is not to teach you the ins and outs of Maven, but rather to just show you the basics of what you need to know about Maven to get up and running smoothly with Hibernate (and Spring).

Okay, Let's Setup Hibernate

The easiest way for me to show you how to go about setting up Hibernate is to do it in a video, so I've recorded one and have included it below for your viewing enjoyment!

Please watch the video above for a full explanation of how to set up your project.

Below I've included the source code I used to create the two Hibernate specific set up files.

Hibernate Configuration Files

There are two files that you'll need to create to get the ball rolling with your Hibernate set up.

  1. PersistenceConfig.java
  2. persistence-mysql.properties

Note: The actual names of these files doesn't actually matter, what matters is that one is a Java file that will be used to configure your Hibernate framework and a properties file.

PersistenceConfig.java

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "com.howtoprogramwithjava.example" })
public class PersistenceConfig
{
	@Autowired
  private Environment env;

  @Bean
  public LocalSessionFactoryBean sessionFactory() {
     LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
     sessionFactory.setDataSource(restDataSource());
     sessionFactory.setPackagesToScan(new String[] { "com.howtoprogramwithjava.example" });
     sessionFactory.setHibernateProperties(hibernateProperties());

     return sessionFactory;
  }

  @Bean
  public DataSource restDataSource() {
     BasicDataSource dataSource = new BasicDataSource();
     dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
     dataSource.setUrl(env.getProperty("jdbc.url"));
     dataSource.setUsername(env.getProperty("jdbc.user"));
     dataSource.setPassword(env.getProperty("jdbc.pass"));

     return dataSource;
  }

  @Bean
  @Autowired
  public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
     HibernateTransactionManager txManager = new HibernateTransactionManager();
     txManager.setSessionFactory(sessionFactory);

     return txManager;
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
     return new PersistenceExceptionTranslationPostProcessor();
  }

  Properties hibernateProperties() {
     return new Properties() {
        {
           setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
           setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
           setProperty("hibernate.globally_quoted_identifiers", "true");
        }
     };
  }
}

persistence-mysql.properties

# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/YOUR_DATABASE_NAME
jdbc.user=your_database_username
jdbc.pass=your_database_password

# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

If you're curious as to where you should create these files, you can just watch the video above and you'll see exactly where they get created.

Free Java Beginners Course

Start learning how to code today with our free beginners course. Learn more.