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:

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:

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:

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:

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:

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.

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.

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

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

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!

34 thoughts on “Hibernate Tutorial part 4 – annotations and maven”

  1. 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 😉

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

  3. 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

  4. 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.

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

    This Tutorial simply rocks!.

  6. 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.

  7. 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.

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

  9. 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

  10. 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

  11. 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.

  12. when i am trying use same example i got the exception,can u please tell me solution,here i am using Mysql

    package com.model;

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

    @Entity
    @Table(name=”Student”)
    public class Student
    {
    private Integer id;
    private String Name;
    private Integer RollNo;
    private String First_Name;
    private String Last_Name;
    public Student() {
    }
    public Student(Integer id, String name, Integer rollNo, String first_Name, String last_Name) {
    super();
    this.id = id;
    Name = name;
    RollNo = rollNo;
    First_Name = first_Name;
    Last_Name = last_Name;
    }
    @Id
    @Column(name = “id”)
    public Integer getId() {
    return id;
    }
    public void setId(Integer id) {
    this.id = id;
    }
    @Column(name = “Name”)
    public String getName() {
    return Name;
    }
    public void setName(String name) {
    Name = name;
    }
    @Column(name = “RollNo”)
    public Integer getRollNo() {
    return RollNo;
    }
    public void setRollNo(Integer rollNo) {
    RollNo = rollNo;
    }
    @Column(name = “First_Name”)
    public String getFirst_Name() {
    return First_Name;
    }
    public void setFirst_Name(String first_Name) {
    First_Name = first_Name;
    }
    @Column(name = “Last_Name”)
    public String getLast_Name() {
    return Last_Name;
    }
    public void setLast_Name(String last_Name) {
    Last_Name = last_Name;
    }
    }

    com.mysql.jdbc.Driver
    password
    jdbc:mysql://localhost:3306/db
    root
    root
    org.hibernate.dialect.MySQLDialect
    true

    package com.controller;

    import javax.transaction.Transaction;

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;

    import com.model.Student;

    public class Test {

    public static void main(String[] args) {
    Configuration cfg=new Configuration();
    cfg.configure();
    SessionFactory sf=cfg.buildSessionFactory();
    Session s=sf.openSession();
    org.hibernate.Transaction tx=s.beginTransaction();
    Student st=new Student();
    st.setId(12);
    st.setName(“nick”);
    st.setRollNo(89647);
    st.setFirst_Name(“rvg”);
    st.setLast_Name(“frd”);
    s.save(st);
    sf.close();
    s.close();
    tx.commit();

    }

    }

    INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
    Exception in thread “main” org.hibernate.exception.SQLGrammarException: Error calling Driver#connect
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:118)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
    at com.controller.Test.main(Test.java:16)
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database ‘db’
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3996)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1284)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2137)
    at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:776)
    at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:352)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:284)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
    … 14 more

Leave a Reply

Your email address will not be published. Required fields are marked *