Singularity Programming

Programming & Math Tutorials

GWT 2.4.0 + Hibernate 3.6.10.Final Tutorial / Example

First of all: you can Download the project files of this tutorial here:

Download this tutorial example clicking here!
– Download the hibernate and other library dependencies clicking here!


One of the first tutorials I’ll post is a Commercial GWT + Hibernate java tutorial.
This is very useful for commercial applications  but it is also useful if game programmers want to put they games on a web site that manages login. So a little overview of the technologies:

Technologies involved:

GWT 2.4.0:

GWT is a very good platform to make communication between client side x server side. This is done using GWT RPC (Remote procedure call).

It’s easy to make a servelet using GWT because almost all the configuration is done in Java!
I’d recommend you to read some tutorials on GWT before integrating with hibernate. It’s very useful to know the GWT structure and concepts, before doing this integration.

Take a look on this Google GWT Tutorial: https://developers.google.com/web-toolkit/doc/latest/tutorial/

Hibernate 3.6.10.Final:

Wiki definition: Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

In other words, with hibernate you can save the Java Objects directly on a database of your choice, e.g. MySQL. You won’t need to manage the MySQL tables manually as doing table creation or table updates etc… Everything is done by Hibernate.
This make the process of doing databases more easy, because you can manage the Java objects  directly, without the necessity of database handling.
Obviously you can configure everything with hibernate, since thread pools to cache. You must read the hibernate documentation for that.

A good hibernate tutorial is on this site: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/tutorial.html

The advantages with this integration rely on:
– With GWT you can handle the GUI interface and Client x Server more easily.
– With Hibernate you can handle database operations more easily.

The code support during the time e.g. 2 years will be much more ‘transparent’ if you use these technologies. Many of the hard-code you’d had to do is done on GWT and Hibernate.

Tutorial: GWT + Hibernate Integration:

Now that you know the advantages of using this integration let’s do it!

First of all, it’s not straightforward doing this integration. Many people get in troble when configuring GWT + Hibernate. There are some peculiarities to follow in ordering to achieve correct configuration of the two technologies. Many exceptions may raise when you do this at first time. You’ll need patience on doing this integration.

ATTENTION:
– In this tutorial we’re using GWT 2.4.0 and Hibernate 3.6.10.Final. I’d recommend you to use this same versions. If you put different versions the tutorial may not work, due to lib incompatibilities.
– don’t miss any lib or even change the version of the libs withouth knowing the compatibilities.

1- GWT Plugin Installation:

GWT 2.4.0 you can install via eclipse update.
The steps for the installation are here: https://developers.google.com/web-toolkit/usingeclipse

In this tutorial we’re using hibernate 3.6.10.Final, you can download it here: http://sourceforge.net/projects/hibernate/files/hibernate3/3.6.10.Final/

2- Create New Web Application Project:


Picture 1: Creating new GWT Project. (Click on picture to enlarge)

Take a look at Picture 2: Uncheck the Google App Engine. Till where I know you cannot currently use Hibernate directly. There are differences between the App Engine datastore and SQL were too great to get the standard Hibernate up and running under App Engine.

Picture 2: Uncheck Google App Engine. (Click to enlarge)

3- Now put the libs on the project.

check your hibernate-distribution-3.6.10.Final folder, contains these libs:

 hibernate3.jar
 war/WEB-INF/lib/required/antlr-2.7.6.jar
 war/WEB-INF/lib/required/commons-collections-3.1.jar
 war/WEB-INF/lib/required/dom4j-1.6.1.jar
 war/WEB-INF/lib/required/javassist-3.12.0.GA.jar
 war/WEB-INF/lib/required/jta-1.1.jar
 war/WEB-INF/lib/required/slf4j-api-1.6.1.jar
 war/WEB-INF/lib/jpa/hibernate-jpa-2.0-api-1.0.1.Final.jar

You must download these .jar individualy:

hibernate-validator-4.0.2.GA
http://repo1.maven.org/maven2/org/hibernate/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA.jar

validation-api-1.1.0.Alpha1.jar
 http://repo1.maven.org/maven2/javax/validation/validation-api/1.1.0.Alpha1/validation-api-1.1.0.Alpha1.jar

log4j-1.2.15.jar
http://mvnrepository.com/artifact/log4j/log4j/1.2.15 or visit the site: http://logging.apache.org/log4j/

slf4j-log4j12-1.6.1.jar
http://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12/1.6.1 or visit the site: http://www.slf4j.org/

Also download the lib files for your db manipulation. We’re using the in memory h2database: http://www.h2database.com and MySQL database. So download the libs:

h2-1.3.165.jar
http://mvnrepository.com/artifact/com.h2database/h2/1.3.165

mysql-connector-java-5.1.6.jar
http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.16

Also, put these files in the root of the source pah, put these files:

log4j.properties -> download link
src/log4j.properties

META-INF/persistence.xml -> download link
src/META-INF/persistence.xml

The Eclipse lib paths will be like that:

Picture 3: Hibernate & other project dependencies
This is a link with all necessary libs: click here.
Attention: The gwt-servelet.jar is not included. You must put it manually when creating a new Google Web Application Project.

4- Put the libs on the source path to clear eclipse code complains:

Click to enlarge

Picture 4: Adding dependencies to path

5- Now that the libs are correclty setup we’ll create an Event class to be handled on hibernate:

Pay attention: The Event class must be saved on server side!

If you dont’ know about GWT client x server communication see this Tutorial from Google GWT Team:
https://developers.google.com/web-toolkit/doc/latest/tutorial/gettingstarted

So let’s see the Event class on server:

package com.webreg.server;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import com.webreg.client.dto.EventDTO;
@Entity
@Table( name = "EVENTS" )
public class Event {
    private Long id;
    private String title;
    private Date date;
    public Event() {
        // this form used by Hibernate
    }
    public Event(String title, Date date) {
        // for application use, to create new events
        this.title = title;
        this.date = date;
    }

    public Event(EventDTO user) {
        this.title = user.getTitle();
        this.date = user.getDate();
    }
    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    public Long getId() {
        return id;
    }
    private void setId(Long id) {
        this.id = id;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "EVENT_DATE")
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public int hashCode() {
        int result = title.hashCode();
        result = 31 * result + date.hashCode();
        return result;
    }
}

Now that we have the Event class you can save it on hibernate (remember on server side):

// saving the data on DB
 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("some_name_you_choose");
 EntityManager entityManager = entityManagerFactory.createEntityManager();
 entityManager.getTransaction().begin();
 entityManager.persist(event);
 entityManager.getTransaction().commit();
 entityManager.close();

As I said before must put the persistence.xml  to sign the hibernate the right classes configuration. This file is the hibernate configuration file for persistence. Here we’re configuring the HSQLB in memory databse:

persistence.xml for HSQLB database:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
 version="2.0">
<persistence-unit name="some_name_you_choose">
  <description>
    Persistence unit for the Envers tutorial of the Hibernate Getting Started Guide
  </description>
  <class>com.webreg.server.Event</class>
  <properties>
    <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
    <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE" />
    <property name="javax.persistence.jdbc.user" value="sa" />
    <property name="javax.persistence.jdbc.password" value="" />
    <property name="hibernate.show_sql" value="true" />
    <property name="hibernate.hbm2ddl.auto" value="create" />
 </properties>
</persistence-unit>
</persistence>

If you want to use MySQL database, you must install MySQL, configure the MySQL, create a database, see how to do a database creation here: http://www.mysqltutorial.org/mysql-create-drop-database.aspx, and configure this database name on the .xml bellow. The tables creation and manipulation will be a hibernate responsibility.

persistence.xml for MySQL database:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="some_name_you_choose">
  <description> 
    Persistence unit for the Envers tutorial of the Hibernate Getting Started Guide 
  </description>
  <class>com.webreg.server.Event</class>
  <properties>
    <property name="datanucleus.storeManagerType" value="true" />
    <property name="hibernate.bytecode.use_reflection_optimizer" value="false" />
    <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
    <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/the_database_you_created" />
    <property name="hibernate.connection.username" value="root" />
    <property name="hibernate.connection.password" value="root" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
    <property name="hibernate.hbm2ddl.auto" value="update"/>
    <property name="show_sql" value="true" />
  </properties>
</persistence-unit> 
</persistence>

The final project structure is this:

Project Structure without DTO

Picture 5: Project structure: saving a object on hibernate (server side). If you need to pass a object from client to server side use DTO, it’s the topic 6 bellow.

6- Managing classes from GWT client side to Hibernate server side.

If you want to send a class from the client side to server side, you must create a class on client side, and another class on server side.

This object on client site is called DTO (Data Transfer Object).

The DTO is necessary because the client side Object is a Javascript one that is transfered to server side via GWT RPC (RPC means Remote procedure call); this Object is not compatible with a java Hibernate Object.

So the solution:
– Create a object/class on client side
– Create a object/class on server side copying the parameters of the client side.

If you have an object on client side and another on server, the’re not the same object, so the compatibility problems about GWT x Hibernate are solved.

See on the example bellow, a new EventDTO is generated on client side and managed on server side:

EventDTO.java (on client side):

package com.webreg.client.dto;

import java.io.Serializable;
import java.util.Date;

public class EventDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private String title;
    private Date date;

    public EventDTO() {
    }

    public EventDTO(String title, Date date) {
        this.title = title;
        this.date = date;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
}

Event.java (on server side: this is an hibernate object)

package com.webreg.server;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import com.webreg.client.dto.EventDTO;
@Entity
@Table( name = "EVENTS" )
public class Event {
    private Long id;
    private String title;
    private Date date;
    public Event() {
        // this form used by Hibernate
    }
    public Event(String title, Date date) {
        // for application use, to create new events
        this.title = title;
        this.date = date;
    }

    // just copy the fields from EventDTO (client side) to
    // this server Event class
    public Event(EventDTO user) {
        this.title = user.getTitle();
        this.date = user.getDate();
    }
    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "EVENT_DATE")
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    } 

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public int hashCode() {
        int result = title.hashCode();
        result = 31 * result + date.hashCode();
        return result;
    }
}

When the server side is called just convert the DTO class to hibernate class, and save it:

Event event = new Event(eventDTO);
// saving the data on DB
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("some_name_you_choose");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(event);
entityManager.getTransaction().commit();
entityManager.close();

Finally the final structure of the project (with DTOs) is this:

Picture 6: Project structure: saving a object on hibernate (server side) with a DTO object from client side.
You must copy the EventDTO fields to Event fields to make a copy avoiding incompatibilities from GWT x Hibernate objects.

Conclusion

It’s not very straightforward doing the configuration, but not very difficult. Just pay attention on each step.
There are many exceptions that can be thrown if you don’t follow every step. So if you have any doubt just comment bellow.
If you find something it could be added (or something wrong) please contact-me!

Tutorial by: Orochi Master

30 responses to “GWT 2.4.0 + Hibernate 3.6.10.Final Tutorial / Example

  1. dersani April 23, 2012 at 11:54 am

    Nice wrap around serval tuts. Could help people who starting up with gwt and hibernate.

  2. simon0191 May 4, 2012 at 5:02 pm

    Thanks ! It was really helpful

  3. robinr May 28, 2012 at 7:20 pm

    Hi, I got this error message “There is no available StoreManager of type “true””
    I was using MySQL as database. Please help me. Thank you

    • Orochi Master May 29, 2012 at 12:02 am

      Did you uncheck the Google App Engine?
      Did you start a new Project from scratch?
      Are you using maven.
      Are you sure you’re using the correct versions of libs?

  4. robinr May 30, 2012 at 11:50 am

    Hi Orochi,
    I didnt uncheck Google App Engine
    I started new Project from scratch
    No maven. I use eclipse 3.5 and GWT 2.4.0, App Engine 1.6.5
    I downloaded libs from this post

    Ty

    • Orochi Master May 30, 2012 at 3:18 pm

      You MUST uncheck Google App Engine.
      Try again.

      I did the process again it worked here.

      • robinr May 30, 2012 at 4:43 pm

        Hi Orochi, it works now
        Thank you very much. The root cause is I didnt uncheck Google App Engine

  5. Ben June 15, 2012 at 11:53 am

    Hi, thank you a lot for this post. In developer mode everything work, but then I copy files from “war” to “webapps” on server I have some troubles… I open my application from a browser, client part is work good but server part isn’t. Can you help me please? Thank you

  6. José Lima July 19, 2012 at 7:55 pm

    Hi Orochi, thanks for the tutorial, but i’m getting this error:
    “javax.persistence.PersistenceException: No Persistence provider for EntityManager named gwt hibernate mysql”
    I’m tried everything… 😦

  7. kains November 8, 2012 at 11:50 am

    nice tutorial…but what about when the FetchType=lazy is there in our entity ??? this will work???

  8. pauriach December 5, 2012 at 1:11 pm

    Awesome tuto, thanks !
    Everything worked perfectly for me. The only thing I would suggest is an example of searching and retrieving an object from the database ?

  9. Juan Pablo January 30, 2013 at 10:40 pm

    In Hibernate we have two possibility to map, with annotations and files. xml
    Does this work with only with annotations in Java classes or served with mapping files also?
    Thank you very much for the tutorial, helped me a lot!
    Greetings!

    • Orochi Master January 31, 2013 at 2:35 am

      It works with hibernate xml files!
      I used annotations because I think it is less verbose.
      But surely it is possible, just exchange the annotations by the hibernate xml configuration it must work. But I didn’t cover this on this tutorial, maybe some peculiarities could emerge….

  10. Anu January 31, 2013 at 7:22 am

    i am new to this technology.i followed ur tutorial ,but i got an error like this javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager.then i have added hibernate-entitymanager library then i got java.lang.ClassNotFoundException: org.hibernate.MappingNotFoundException.please give me a solution

    • Orochi Master March 3, 2013 at 11:36 pm

      It appears that the you are not using the annotations, you are using the hibernate via .hbm.xml configuration.
      It’s difficult to find a problem without sources. I’d recommend you to restart a new project tutorial from scratch using the exact libs of this tutorial.
      Or post this error you’re finding on stackoveflow…

  11. jvdeveloppement April 25, 2013 at 10:43 am

    i have a question ( a silly one), how can i run the thing ?

    • Orochi Master May 20, 2013 at 7:02 pm

      GWT code? You can download it. It’s the first thing I wrote.
      If you’re asking about GWT GUI code, there isn’t much of this code because is a tutorial about GWT + Hibernate.

  12. Tony November 11, 2013 at 11:03 pm

    Hi Orochi!, thanks 1000Times for this tuto!
    But How can I generate my DTOs , if I already have a databe mysql with many tables??

    • Orochi Master November 16, 2013 at 1:12 pm

      Automatically??? Maybe I’m wrong, but I think it’s not very good to do it.
      Try finding out integrating hibernate with existing mysql database. As hibernate connects to mysql or any database, you’ll could write DTO’s to hibernate saving without concerning about mysql tables.
      BUT, I would done a totally new database and populate the data from old mysql database to this new one. I think this could bring more work, but you’d know the work step by step you’re doing without magic.

    • Orochi Master April 23, 2014 at 6:23 pm

      I know there is the Hibernate Tools 3.4 plugin for Eclipse.
      I never used it, but I know it works well. Search for it.

  13. Marcis June 27, 2014 at 5:01 pm

    Really nice tutorial. All seem to work fine- expect no data is inserted into my database. I get no errors so it should be OK. I added “entityManager.flush()”, but that didn’t help me either. I recieve this console message:

    Info: Local Datastore initialized:
    Type: High Replication
    Storage: D:\Eclipse workspace\my_project\myProject\war\WEB-INF\appengine-generated\local_db.bin

    Any ideas why no data is inserted?

    • Orochi Master July 1, 2014 at 1:18 pm

      No errors?
      local_db.bin isn’t Google AppEngine stuff? Take a look at Step 2: Create New Web Application Project.
      I never used GoogleAppEngine with hibernate. Try finding a tutorial of it.

  14. simon 27 September 20, 2014 at 9:23 pm

    Hello there I am so excited I found your website, I really found you by mistake, while
    I was searching on Askjeeve for something else, Anyhow I am here now
    and would just like to say thanks a lot for a fantastic post and a all
    round enjoyable blog (I also love the theme/design), I don’t have
    time to read it all at the minute but I have book-marked it and also added in your RSS feeds,
    so when I have time I will be back to read much more, Please do keep up the
    superb jo.

  15. cloud computing October 19, 2014 at 4:41 pm

    excellent publish, very informative. I’m wondering why the opposite
    specialists of this sector do not realize this.

    You must continue your writing. I’m confident, you have a great readers’ base already!

  16. Edison OKPE January 20, 2016 at 7:03 am

    Very helpful indeed !

Leave a comment