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!
November 3rd, 2008 - 04:23
Nice post! It helped me sort out a problem very quickly. Thanks.
January 28th, 2009 - 15:28
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
February 8th, 2009 - 04:31
Thanks for the post; it gave me just enough info to get rid of using mapping files.
February 10th, 2009 - 16:56
Thanks a lot for this wonderful tutorial, it’s unbelievably hard to find any clear documentation regarding the use of Maven and Hibernate.
February 13th, 2009 - 15:07
Its very nice tutorial for beginers for hibernate… thanks very much….
February 17th, 2009 - 11:00
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
February 19th, 2009 - 18:03
Your a *..
Thank you.
Do you have one on Hibernate/Spring and Maven
February 23rd, 2009 - 11:30
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.
February 25th, 2009 - 21:22
Simple nice. The analysis has made the subject of Hibernate simplyfied
March 9th, 2009 - 09:37
And if your not publishing ur 5 part on this subject, I gonna not to talk to you.
This Tutorial simply rocks!.
March 16th, 2009 - 12:48
Hi,
nice one!
i recommend video how to setup Hibernate environment at:
http://hibernatetutorial.com/Hibernate-tutorial-how-to-set-up-basic-Hibernate-development-environment.html
July 7th, 2009 - 18:39
Very useful hibernate jumpstart and helpful tutorial series. Thanks a bunch.
July 27th, 2009 - 20:14
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.
September 27th, 2009 - 19:42
Since you asked for it
… here is the feedback: nice work. Got it up and running in half an hour.
October 17th, 2009 - 08:23
very good one, hope i do get Hibernate, Spring and some form of cache apps from you because you are best.
October 29th, 2009 - 17:12
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.
January 14th, 2010 - 17:21
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
February 17th, 2010 - 23:51
Very nice tutorial. Worked well for me.
March 27th, 2010 - 06:33
great work… thanks very much!!
June 2nd, 2010 - 20:27
great tutorials, part 1-4, looking fwd for the 5th part
, good job!