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;@
Entitypublic 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!