Hibernate 4.3 Introduction Tutorial

An introduction to Hibernate 4

In this article I will show you how can you use Hibernate 4,  along with a simple example application available to try out what you read about.

What is Hibernate and why should I care?

Hibernate was created to leverage the connection between Java applications and relational databases because it is hard to map back and forth between a database table and a Java object.

And because Hibernate does this, it reduces development time which is consumed by JDBC query-execution and data mapping.

Getting Hibernate

To get the latest version of Hibernate, just visit this site. For this article I will use the version 4.3.10.Final.

If you download and extract the package you can see some sub-folders in the lib folder. Everything under required is required for any project using Hibernate. The other folders contain libraries for special cases. For example under jpa you find the library providing the JPA entity manager support.

Alternatively you can set up a Maven project and add Hibernate as a dependency. In this case you do not need to take care about the other required dependencies of Hibernate, which come along in the required package with the bundle-download. Using Maven is more simple and straightforward so I will use Maven as dependency management.

A simple example

In the simple example I will create a Java application which stores information about books in the database. The database will be an H2 memory database for the sake of simplicity.

Dependencies are managed with Maven and the output is an executable JAR with all dependencies.

The entity

The entity I will store in the database is the following:

package example;

public class Book {

   private String isbn;
   private String title;
   private String author;

   Book() {
   }

   public Book(String isbn, String title, String author) {
       this.isbn = isbn;
       this.title = title;
       this.author = author;
   }

   public String getIsbn() {
       return this.isbn;
   }

   public String getTitle() {
       return this.title;
   }

   public void setTitle(String title) {
       this.title = title;
   }

   public String getAuthor() {
       return this.author;
   }

   public void setAuthor(String author) {
       this.author = author;
   }

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

The no-argument constructor is a requirement for all persistent classes because Hibernate creates the object instances per reflection. In this case this constructor is private to prevent creation of books without information.

The dependencies

To get the app running, we need two dependencies in the project: Hibernate and H2. To do this, add the following to the pom.xml:

<dependencies>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.10.Final</version>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.187</version>
</dependency>
</dependencies>

Now we are ready to continue on.

Configuring Hibernate

Hibernate needs some configuration to get started. This you need to include in the hibernate.cfg.xml file. It is plain old XML. It contains the database connection properties and the entity mapping files inclusive location.

<!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 settings -->
       <property name="connection.driver_class">org.h2.Driver</property>
       <property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
       <property name="connection.username">sa</property>
       <property name="connection.password"/>

       <!-- JDBC connection pool (use the built-in) -->
       <property name="connection.pool_size">1</property>

       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.H2Dialect</property>

       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>

       <!-- Drop and re-create the database schema on startup -->
       <property name="hbm2ddl.auto">create</property>

       <mapping resource="hibernate_example/hbm/Book.hbm.xml"/>

   </session-factory>

</hibernate-configuration>

The entity mapping

To map the right fields to the right column in the database, Hibernate requires a mapping file for the entities. These are located in the .hbm.xml files which start with the entity’s name. In this example Book.hbm.xml.

<!DOCTYPE hibernate-mapping PUBLIC
     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="hibernate_example">

   <class name="Book" table="BOOKS">
       <id name="isbn" type="string"/>
       <property name="title"/>
       <property name="author"/>
   </class>

</hibernate-mapping>

The main method

To use the application with Hibernate we still need an entry point — and in Java this is the main method. To start, we need some configuration, like creating a session with a session factory… So let’s look at the code how it goes:

public class Main {

   public static void main(String[] args) {
       final Configuration configuration = new Configuration().configure();
       final StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
       final SessionFactory factory = configuration.buildSessionFactory(builder.build());
       final Session session = factory.openSession();
       final Book book = new Book("93939398948 ", "Java 8", "Author");
       session.beginTransaction();
       session.save(book);
       session.getTransaction().commit();
       final List<Book> books = session.createCriteria(Book.class).list();
       System.out.println("\n----\n");
       System.out.println(MessageFormat.format("Storing {0} books in the database", books.size()));
       for (final Book b : books) {
           System.out.println(b);
       }
       System.out.println("\n----\n");
       session.close();
       factory.close();
   }
}

 

After running the application the console should have some log messages and the one book added to the database:
—-

Storing 1 books in the database
Java 8 by JBT (ISBN:9393939894

—–

Conclusion

Hibernate gives a nice feature to leverage mapping between Java objects and relational databases. Naturally this sample application does not show the full power of Hibernate: for better user experience you could add a user interface to create and list books in the application.

In a later article I will show how to get rid of the XML configuration (called by some developers as the “XML-Hell”) and use annotations instead. So stay tuned.

You can find and download the sources of the application here.

Series Navigation<< Hibernate Framework BasicHibernate 4 annotations Configuration >>
By | 2017-07-10T18:49:53+00:00 June 28th, 2015|Hibernate|4 Comments

About the Author:

4 Comments

  1. 454 August 28, 2016 at 6:04 am - Reply

    ok

  2. Gluta Lachel Original March 2, 2017 at 3:14 pm - Reply

    It’s going to be ending of mine day, but before finish I am reading this impressive article to
    increase my know-how.

  3. dillip April 11, 2017 at 7:39 am - Reply

    But where is the util class.

    • Mushraful May 3, 2017 at 1:05 pm - Reply

      I read the article and as far as I understood the framwork does the connection an other stuffs with the details we gave in the configuration file

Leave A Comment