Ian P. Christian's Personal Blog Random witterings from pookey

26Sep/0833

Hibernate Tutorial part 4 – annotations and maven

In the last part of my hibernate tutorials I showed how to get a simple application inserting data into a database. This part doesn't expand on that in terms of features, in fact, this tutorial actually does less! However, the last tutorial required you to download a whole load of JAR files, and manage all dependencies. I did make this easy for you, by providing a single download and telling you exactly what you needed - but this time, I'm going to make it even easier! The purpose of this is to get you started with Hibernate annotations, and Maven. All you need is a text editor, a working Java 5 or higher install, and Maven.

If you've never heard of Maven before, you might want to look at my getting started with spring and maven tutorial

The first step we want to take is to create our project. We're going to use Maven to do this, by doing as follows:

mvn archetype:generate --batch-mode \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DgroupId=uk.co.pookey.hibernate \
  -DartifactId=hibernate

If you want to know more about what those options mean, you should have a look at the Maven documentation. This command will create a skeleton project in the hibernate directroy. Change into this directory, and open up pom.xml in your editor. You'll want to change it to read 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>uk.co.pookey.hibernate</groupId>
  <artifactId>hibernate</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>hibernate</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
       <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.0.2</version>
          <configuration>
              <source>1.5</source>
              <target>1.5</target>
          </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.2.6.ga</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>3.3.1.GA</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
  </dependencies>
</project>

The important things to note here are that we've changed the config of maven-compiler-plugin to compile for java 1.5 - without doing this annotations would not work. Also, notice the dependencies we've added - we've told maven we need the hibernate, hibernate-annotations, and mysql connector libraries. Maven will take care of downloading them, and all of their dependencies when we build - you no longer need to worry about them!

Our next step is to configure our hibernate settings. As before, we do this in hibernate.cfg.xml. The location of the file is different though, you'll want to use src/main/resources/hibernate.cfg.xml, and input something like I have 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">
<hibernate-configuration>
  <session-factory>
    <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
    <property name="connection.username">root</property>
    <property name="connection.password">"Schipiaf2</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
    <property name="show_sql">true</property>
 
    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">create</property>
 
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <property name="current_session_context_class">thread</property>
 
  </session-factory>
</hibernate-configuration>

That's most of the configuration done - it's time to write some code! When we created our project, Maven created a class uk.co.pookey.App in src/main/java/uk/co/pookey/hibernate/App.java. For this tutorial, we're just going to use that class. To use annotations, we need to use the AnnotationConfiguration class, so we'll simply modify our App.java file as follows:

package uk.co.pookey.hibernate;
 
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class App
{
    public static void main( String[] args )
    {
        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
 
        Session session = sessionFactory.getCurrentSession();
 
    }
}

That's it! We have hibernate installed, configured, and running. We can test that it's all working now by asking maven to compile and run our project. There will be no useful output, but if this is the first time you're running Maven, you'll see it download all the required JAR files, and output a whole load of stuff as your application and hibernate start. Here's the command you need:

mvn clean compile exec:java -Dexec.mainClass=uk.co.pookey.hibernate.App

Now it's time to add a model to our project. We're going to put models in the uk.co.pookey.hibernate.model package, so create the directroy src/main/java/uk/co/pookey/hibernate/model. Within this directory, we want to create a Blog class, which is virtually identical to what we've seen in previous parts of this tutorial. The only differences are the import statements, and the annotations.

package uk.co.pookey.hibernate.model;
 
import java.util.Date;
 
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
 
@Entity
public class Blog {
 
  private Long id;
 
  private String subject;
 
  private String body;
 
  private Date createdAt;
 
  @Id
  @GeneratedValue
  public Long getId() {
    return id;
  }
 
  public void setId(Long id) {
    this.id = id;
  }
 
  public String getSubject() {
    return subject;
  }
 
  public void setSubject(String subject) {
    this.subject = subject;
  }
 
  public String getBody() {
    return body;
  }
 
  public void setBody(String body) {
    this.body = body;
  }
 
  public Date getCreatedAt() {
    return createdAt;
  }
 
  public void setCreatedAt(Date createdAt) {
    this.createdAt = createdAt;
  }
}

Notice we've not annotated all of our properties, in fact - we only did the Id field. We need to do the Id field to inform hibernate this is our identifier column - hibernate will 'guess' the other fields magically, so that's really all we need to do here! Much easier then writing an XML file as we did before. One more thing we do need to do is modify our hibernate.cfg.xml to tell it about our new class.

<hibernate-configuration>  
  <session-factory>
  ....
    <mapping class="uk.co.pookey.hibernate.model.Blog" />
  </session-factory>
</hibernate-configuration>

We are nearly finished now - all that remains is to create a Blog and save it. Below is the modified App class.

package uk.co.pookey.hibernate;
 
import uk.co.pookey.hibernate.model.Blog;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class App
{
    public static void main( String[] args )
    {
        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
 
        Session session = sessionFactory.getCurrentSession();
 
        Transaction tx = session.beginTransaction();
 
        Blog b = new Blog();
        session.save(b);
 
        tx.commit();
    }
}

That's it! We're done. Here is the output when we run our application, trimmed to show only the exciting bits.

$ mvn clean compile exec:java -Dexec.mainClass=uk.co.pookey.hibernate.App 
...
26-Sep-2008 22:46:56 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: schema export complete
Hibernate:
    insert
    into
        Blog
        (body, createdAt, subject)
    values
        (?, ?, ?)
...

Here is the source code, should you want a copy: hibernate-part4.tar.gz. Notice this file is considerably smaller than the previous example - as it doesn't' need to contain the JAR files - Maven will sort that out for you! This of course is just an introduction to annotations and hibernate. Perhaps if I write part 5, I'll show more. Hopefully though this is enough to get you started and ready to experiment yourselves.

I'm only writing this article because of the positive feedback I got from previous parts - your feedback does mean a lot to me (sad isn't it? ;) ) - so if you found this useful please do leave a comment letting me know!

Filed under: geek, java Leave a comment
Comments (33) Trackbacks (0)
  1. Nice post! It helped me sort out a problem very quickly. Thanks.

  2. Nice tutorial.
    I just starting with hibernate. This tutorial me helped very much.
    Thanx.

    p.s. spam prevention image/text is very difficult to read. I recognise it after five-six refreshing ;)

  3. Thanks for the post; it gave me just enough info to get rid of using mapping files.

  4. Thanks a lot for this wonderful tutorial, it’s unbelievably hard to find any clear documentation regarding the use of Maven and Hibernate.

  5. Its very nice tutorial for beginers for hibernate… thanks very much….

  6. Keep up the good work! Thank you for this great tutorial. Can you recommend me a good book that I can learn from how to work with Hibernate in a real life application?
    Best regards,
    Danut

  7. Your a *..

    Thank you.
    Do you have one on Hibernate/Spring and Maven

  8. Thank you very much for your eforts to make this unique tutorial. I couldn’t find any other tutorial so lean. It is perfect in that one can find just he want to know without dealing with confusing information. Even hibernate offical site presents a confusing tutorial that mixed ant and maven topics. So thanks a lot again.

  9. Simple nice. The analysis has made the subject of Hibernate simplyfied

  10. And if your not publishing ur 5 part on this subject, I gonna not to talk to you.

    This Tutorial simply rocks!.

  11. Very useful hibernate jumpstart and helpful tutorial series. Thanks a bunch.

  12. Nice tuto because of the maven part. But unfortunately it’s not working for me. I get the following error:
    :
    :
    :
    insert
    into
    Blog
    (body, createdAt, subject)
    values
    (?, ?, ?)
    27.07.2009 21:53:06 org.hibernate.AssertionFailure
    SCHWERWIEGEND: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at ja……………
    :
    :
    :
    It’s just a small part from the error message. Maybe you know about this problem or have an idea. If you want I can also send you the complete error message.

  13. Since you asked for it :) … here is the feedback: nice work. Got it up and running in half an hour.

  14. very good one, hope i do get Hibernate, Spring and some form of cache apps from you because you are best.

  15. Thanks for sharing.
    There is a problem for downloading all jars from Maven2 repository though, but maven give instructions on how to get it from Sun and install it to local repository.

  16. In this post I detail simple instructions for installing Glassfish v3 onto Ubuntu (although it will work just as well with Redhat, debian, and anything else). I also show how to create and deploy a simple WAR using Maven. Installing software

  17. Very nice tutorial. Worked well for me.

  18. great work… thanks very much!!

  19. great tutorials, part 1-4, looking fwd for the 5th part :D , good job!

  20. very good one…..great work..

  21. simple and helpful!

  22. nice one man! thanks for this. I would appreciate if you can also write something integrating Jersey with hibernate.

  23. Your all 4 parts of the tutorial have really been very useful.
    Great work.

  24. Thank you for your tutorial, thank you for taking time to writing for us.
    Thank you with regards
    Nivi

  25. I am getting this error while building:

    Missing:
    ———-
    1) javax.transaction:jta:jar:1.0.1B

    Try downloading the file manually from:
    http://java.sun.com/products/jta

    Then, install it using the command:
    mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile=/path/to/file

    Alternatively, if you host your own repository you can deploy the file there:
    mvn deploy:deploy-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]

    Path to dependency:
    1) uk.co.pookey.hibernate:hibernate:jar:1.0-SNAPSHOT
    2) org.hibernate:hibernate:jar:3.2.6.ga
    3) javax.transaction:jta:jar:1.0.1B

  26. Actually, I was able to resolve it. for others who hit similar issue:-

    1. i downloaded the zip file (jar file was not present there) from the location in error: (http://java.sun.com/products/jta).
    2. save it somewhere on your disk
    3. Use the cmd in the error to install it: -
    mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile=/path/to/file

    bingo!
    now execute the app:-

    mvn clean compile exec:java -Dexec.mainClass=uk.co.pookey.hibernate.App

  27. Great tutorial.
    I had some issues running/testing the app. Specifically, when I ran the app twice, the second time I got an error saying “couldn’t create the table Blog – table already exists”, and the throwing an exception later that it couldn’t save because table didn’t exist. When I looked at mysql, sure enough, the table wasn’t there. When I restarted mysql, it worked the first time, then I got the same error when I ran it after that, until I restarted the DB.
    The simple fix is to make sure the DB default-storage-engine is INNODB. I use a mac and I just added this to the file /etc/my.cnf. You might have to do this in my.ini or similar file for your system. I hope this helps some.

  28. Very useful article. Thanks a lot

  29. You can replace all hibernate deps with following:

    org.hibernate
    hibernate-core
    3.6.3.Final

  30. really really useful
    Thank u

  31. Please how do i make my gwt hibernate work with marven. I creating the pom.xml file bt i get errors wen ever i test it.

  32. AAAAAAAAAAA!!!! Thanks thanks thanks from a totally newbie! xD


Leave a comment

No trackbacks yet.