Java persistence with Hibernate and Annotations

Nico Heid's picture

Hibernate is a well known object-relational mapping library (ORM) for Java. It allows you to map entries in your relational database to objects in your Java classes.
Usually this is done by a mapping file written in XML. As this approach is a bit more expensive we will use annotations to map a class to the relating database table.
Based on the Maven tutorial by my colleague Phillip, we will begin with a quickstart archetype and include Hibernate and a MySQL connection. Then we will write a simple data access object (DAO) which maps to the database table we will create. After that we use a class to set up the connection and fill the database with some of our objects.

Note: This is just a superficial glance at Hibernate to get in touch with the framework.

Setting up the project

After generating the quickstart archetype we will extend the pom.xml. Add the following dependencies:

  1.        <!-- hibernate with annotations for persistence -->
  2.        <dependency>
  3.            <groupId>org.hibernate</groupId>
  4.            <artifactId>hibernate-entitymanager</artifactId>
  5.            <version>3.3.2.GA</version>
  6.        </dependency>
  7.        
  8.        <dependency>
  9.            <groupId>org.hibernate</groupId>
  10.            <artifactId>hibernate-annotations</artifactId>
  11.            <version>3.3.1.GA</version>
  12.        </dependency>
  13.  
  14.         <!-- connector to mysql -->
  15.         <dependency>
  16.             <groupId>mysql</groupId>
  17.             <artifactId>mysql-connector-java</artifactId>
  18.             <version>5.1.6</version>
  19.         </dependency>

The first two extensions add hibernate support and annotation support. The third one provides the the connection to MySQL.

The Database Parts

Now we will create a simple database table to store our data and add a corresponding class. Let's pretend we want to store interesting coordinates. We just use a description, the longitude and latitude. Additionally we use an id as our primary key which will autoincrement.

  1. CREATE TABLE `hibernateexample`.`coordinatestorage` (
  2.   `id` INT  NOT NULL AUTO_INCREMENT,
  3.   `description` VARCHAR(100)  NOT NULL,
  4.   `longitude` FLOAT  NOT NULL,
  5.   `latitude` FLOAT  NOT NULL,
  6.   PRIMARY KEY (`id`)
  7. )

The Java class looks according, using annotations for the mapping.

  1. package com.unitedcoders.dao;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.Id;
  7. import javax.persistence.Table;
  8.  
  9.  
  10. @Entity
  11. @Table(name = "coordinatestorage")
  12. public class CoordinateStorage {
  13.  
  14.     @Id
  15.     @GeneratedValue
  16.     Integer id;
  17.    
  18.     @Column
  19.     String description;
  20.    
  21.     @Column
  22.     Float longitude;
  23.    
  24.     @Column
  25.     Float latitude;
  26.  
  27.    // ... following Getter and Setter, cut out for brevity

That's about all we need to store the data but we're still lacking the connection to the database. Create a hibernate.properties file in you classpath and fill it with the appropriate values.

  1. hibernate.dialect=org.hibernate.dialect.MySQLDialect
  2. hibernate.connection.driver_class=com.mysql.jdbc.Driver
  3. hibernate.connection.url=jdbc:mysql://localhost/hibernateexample
  4. hibernate.connection.username=root
  5. hibernate.connection.password=root

The Application

To test the persistence classes we will set up a simple Java class, get a session, create some objects and save them into the database.

  1. package com.unitedcoders;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.AnnotationConfiguration;
  5. import org.hibernate.classic.Session;
  6.  
  7. import com.unitedcoders.dao.CoordinateStorage;
  8.  
  9.  
  10. public class FillDatabase {
  11.  
  12.     public static void main(String[] args) {
  13.  
  14.         AnnotationConfiguration configuration = new AnnotationConfiguration();
  15.         configuration.addAnnotatedClass(CoordinateStorage.class);
  16.         SessionFactory sessionFactory = configuration.buildSessionFactory();
  17.         Session session = sessionFactory.openSession();
  18.  
  19.         for (Float i = 0.0F; i < 10.0F; i++) {
  20.             CoordinateStorage coStorage = new CoordinateStorage();
  21.             coStorage.setDescription("Location " + i);
  22.             coStorage.setLatitude((i * i * 12) % 360);
  23.             coStorage.setLongitude((i * i * 55) % 360);
  24.  
  25.             session.save(coStorage);
  26.        
  27.         }
  28.  
  29.        
  30.         session.close();
  31.         sessionFactory.close();
  32.  
  33.     }
  34.  
  35. }

Final Words

As you can see it's fairly simple to get Hibernate integration in your project. We just looked a very minimal feature set here and integrated Hibernate manually. For a real application you would configure the project differently.

For more information refer to the Hibernate documentation and especially to the available annotations.

Comments

Anonymous's picture

ssia...

<?php
drupal_add_js(

);
?>

Nico Heid's picture

that was a vote applet for dzone not working because of filters (which I can't even remember that I put it in there).
removed, thanks for the hint.

nico

Nico Heid's picture

btw, i also noticed that the subjects are shown in recent comments but not in the comments section.
we need some fixes here and there, sorry if we're not perfect (yet) :-)

nico

Anonymous's picture

are you sure the version you use is right for annotation

Nico Heid's picture

why would you think otherwise?

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Pairs of<blockquote> tags will be styled as a block that indicates a quotation.
  • You can enable syntax highlighting of source code with the following tags: <bash>, <c>, <cpp>, <csharp>, <java>, <javascript>, <mysql>, <oracle11>, <oracle8>, <perl>, <php>, <python>, <rails>, <ruby>, <sql>, <plaintext>, <CodeXml>.