Hibernate, Maven and HSQL – Example Project (Using Annotations)

SHARE & COMMENT :

In this tutorial we will write a simple Java project to demonstrate Hibernate, HSQL and Maven using Java 5 Annotations. For this we will use our previous example in the post Hibernate, Maven and HSQL – Example Project (XML Mapping)) as base and convert it from XML Mapping to Annotation.
HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here. If you are beginner for hibernate, please read the articles about introduction to hibernate, interceptors in hibernate and spring & hibernate integration. We also recommend good reference books for learning hibernate in our post about hibernate books.hibernate.

Following are the tools and technologies required for this project:

1. Generating Maven Java project compatible with Eclipse

Follow the steps in the post Hibernate, Maven and HSQL – Example Project (XML Mapping)) to create project structure. Or you can directly download the source code from above post in Eclipse and rename the project in eclipse as HibernateHelloWorldAnnotation.

2.Updating the Hibernate dependency in pom.xml

As we are going to use Annotation mapping in Hibernate we will update our existing pom.xml file as below:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>net.javabeat.hibernate</groupId>
 <artifactId>HibernateHelloWorldXML</artifactId>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>HibernateHelloWorldXML</name>
 <url>http://maven.apache.org</url>
 <dependencies>
   <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>3.8.1</version>
     <scope>test</scope>
   </dependency>
<!-- Hibernate library dependecy start -->
 <b> <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-annotations</artifactId>
     <version>4.1.9.Final</version>
  </dependency></b>
  <dependency>
     <groupId>org.hsqldb</groupId>
     <artifactId>hsqldb</artifactId>
     <version>2.2.9</version>
  </dependency>
  <dependency>
     <groupId>dom4j</groupId>
     <artifactId>dom4j</artifactId>
     <version>1.6.1</version>
  </dependency>
  <dependency>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     <version>1.1.1</version>
  </dependency>
  <dependency>
     <groupId>commons-collections</groupId>
     <artifactId>commons-collections</artifactId>
     <version>3.2.1</version>
  </dependency>
  <dependency>
     <groupId>cglib</groupId>
     <artifactId>cglib</artifactId>
     <version>2.2</version>
  </dependency>
  <dependency>
     <groupId>asm</groupId>
     <artifactId>asm</artifactId>
     <version>4.0</version>
  </dependency>
  <dependency>
     <groupId>dom4j</groupId>
     <artifactId>dom4j</artifactId>
     <version>1.6.1</version>
  </dependency>
  <dependency>
      <groupId>ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>1.2.3</version>
  </dependency>
  <dependency>
      <groupId>hibernate-tools</groupId>
      <artifactId>hibernate-tools</artifactId>
      <version>3.2.3.GA</version>
  </dependency>
  <dependency>
      <groupId>jta</groupId>
      <artifactId>jta</artifactId>
      <version>1.1</version>
  </dependency>
  <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.11</version>
  </dependency>
  <dependency>
      <groupId>oscache</groupId>
      <artifactId>oscache</artifactId>
      <version>2.1</version>
  </dependency>
  <dependency>
      <groupId>persistence-api</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0</version>
   </dependency>
  <!-- Hibernate library dependency end -->
</dependencies>
</project>
 

As a next step, let’s execute the following command so that maven will download all the required JARs and update eclipse classpath. Go to the directory of the project (in our case it is C:\HibernateHelloWorldXML) and execute the following command:

mvn eclipse:eclipse

This step is optional. If your Eclipse has Maven plugin installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by following these instructions : Right click on project > Maven > Enable Dependency Management.

3. Delete the unused Hibernate Mapping file

The file src\main\resources\net\javabeat\hibernate\Contact.hbm.xml is not required anymore. Delete this file from the project.

4. Update the Model class file

We will add simple annotations to the model class (src\main\java\net\javabeat\hibernate\Contact.java) as below:

package net.javabeat.hibernate;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Model class for Conact
 */
@Entity
@Table(name="CONTACT")
public class Contact implements Serializable {
   @Id
   @GeneratedValue
   private Integer contactId;

   @Column(name="name")
   private String name;

   public Contact() {
   }

   public Integer getContactId() {
      return contactId;
   }

   public void setContactId(Integer contactId) {
      this.contactId = contactId;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

}

5.Update the Hibernate Utility class

In our previous post for XML mapping, we were using Configuration class to generate SessionFactory object. In HibernateUtil we had following line of code:

sessionFactory = new Configuration().configure().buildSessionFactory();

We will update this and use AnnotationConfiguration instead of Configuration(). The updated HibernateUtil.java file is as below:

package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
   private static final SessionFactory sessionFactory;
   static {
      try {
	   sessionFactory = new AnnotationConfiguration().configure()
	      .buildSessionFactory();
	   } catch (Throwable ex) {
	   System.err.println("Initial SessionFactory creation failed." + ex);
	   throw new ExceptionInInitializerError(ex);
      }
   }

   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }
}

6. Update Hibernate Configuration file

The configuration file hibernate.cfg.xml, needs to be changed to add the new Annotation based entity class Contact.java instead of old XML Mapping Contact.hbm.xml. The updated src\main\resources\hibernate.cfg.xml is as below:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!-- Database connection settings, Connect to HSQL, IN Memory  -->
    <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
    <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
    <property name="connection.url">jdbc:hsqldb:mem:test</property>
    <property name="connection.username">sa</property>
    <property name="connection.password"></property>

     <!-- JDBC connection pool (use the built-in) -->
     <property name="connection.pool_size">1</property>
     <property name="show_sql">true</property><property name="format_sql">true</property>
     <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
     <!--create the database schema on startup if required -->
     <property name="hbm2ddl.auto">update</property>
     <mapping class="net.javabeat.hibernate.Contact"></mapping>
  </session-factory>
</hibernate-configuration>

Here we have replaced

<mapping resource="net/javabeat/hibernate/Contact.hbm.xml"></mapping>

with

 <mapping class="net.javabeat.hibernate.Contact"></mapping>

7. Final project structure

Once you have created all these source files, your project structure should look like following:
final_proj_stuct_annotation

8. Execution of the above code

Now let us execute the code we created above. Let’s run the App class.
Right click on App.java >Run As > Java Application.
On start of each thread, a database schema will be created and the following actions will happen.

    • Each time a new thread starts the database schema will change the existing one as we have set hbm2ddl.auto option to update.
    • The SQL statement generated gets displayed on the console. This is set using the show_sql option in the hibernate configuration file.

Output on the console:

Maven + Hibernate + HSQL
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    select
        contact0_.contactId as contactId0_,
        contact0_.name as name0_
    from
        CONTACT contact0_
Jiya
Manisha
Riya

Summary

In this post we updated our previous Java project from post Hibernate, Maven and HSQL – Example Project (XML Mapping)) using Maven and made it compatible with eclipse. Then we updated the Hibernate configuration file and also deleted the hibernate mapping file. We also updated our Model class with Java annotations. We used a simple HSQL database, to insert records into CONTACT table and also listed these records. In the next article we shall look into Hibernate Association (One-to-one mapping(XML mapping)). If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here

Comments

comments

About Manisha Patil

Manisha S Patil, currently residing at Pune India. She is currently working as freelance writer for websites. She had earlier worked at Caritor Bangalore, TCS Bangalore and Sungard Pune. She has 5 years of experience in Java/J2EE technologies.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better