About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial

This step by step guide will present how to develop a simple web application using Google’s Web Toolkit (GWT) for the rich client and Spring as the back – end, server side framework. The sample web application will provide functionality to make CRUD (Create Retrieve Update Delete) operations to a database. For the data access layer we will use JPA over Hibernate and for a database we will use Hypersonic. Of course you can change the configuration and use whatever you like. We will deploy the web application to an Apache – Tomcat instance.

Our preferred development environment is Eclipse, so as a prerequisite you must have Eclipse with GWT support installed. The installation of the GWT plugin for Eclipse is out of the scope of this tutorial and will not be discussed. Nevertheless you will need the following components :

In order to properly integrate Spring with GWT at runtime, we must provide all necessary libraries to the web application. So copy the files listed below under /war/WEB-INF/lib (copy the relevant files if you are using different versions)

We now have to take care of dependences for our Eclipse project. The following jars should be included in the Java build path of the project :

hibernate-jpa-2.0-api-1.0.0.Final.jar

org.springframework.beans-3.0.1.RELEASE-A.jar

org.springframework.context-3.0.1.RELEASE-A.jar

org.springframework.core-3.0.1.RELEASE-A.jar

org.springframework.orm-3.0.1.RELEASE-A.jar

org.springframework.transaction-3.0.1.RELEASE-A.jar

The next step is to provide hooks for the web application so as to load the Spring context upon startup and to allow for spring4gwt to intercept RPC calls between the client and the server and transform them to Spring service invocations.

The url-pattern child element of the servlet-mapping element for the springGwtRemoteServiceServlet servlet, should be changed to whatever your GWT module name is e.g. {module_name}/springGwtServices/*, the module name is defined in {project_name}.gwt.xml file (here GWTSpring.gwt.xml) located at the root of the base package of the project under /src folder

You can change the name of spring4gwt servlet (springGwtRemoteServiceServlet here) to whatever you like

To continue we have to create the persistence.xml file so as to describe the connection with the database using JPA. The pesistence.xml file must be located inside a META-INF directory which in turn has to be accessible by the web application at runtime (on the classpath). To fulfill the aforementioned requirements we have to create the META-INF folder under the project’s /war/WEB-INF/classes folder. To do so we create a new source folder under the name e.g. “resources” and create the META-INF folder inside it. Finally create the persistence.xml file inside the /resources/META-INF folder. An example persistence.xml is presented below

In the last part of this tutorial we are going to present the Data Transfer Object (DTO) for transferring data between the client and the server, the Data Access Object (DAO) that is used to access the database and the Spring service to expose functionality to the GWT Web client.

The DTO is an object that can be used by both the client and the server, thus you should create a “dto” subpackage under the “shared” package and place the DTO there. We are going to create an EmployeeDTO containing information for an employee like below

The DAO object will be used to access the database and perform CRUD (Create Retrieve Update Delete) operations. It is a server side component so it should be placed under the “server” subpackage of our project. Create a “dao” subpackage and place the DAO there. An example DAO is presented below

As you can see the EmployeeDAO class extends a basic DAO class (JpaDAO). The EmployeeDAO class can contain specific queries concerning the EmployeeDTO object, but all CRUD operations can be handled from the basic DAO class (JpaDAO). Place the JpaDAO class at the same level as the EmployeeDAO class, under the “dao” subpackage. Below we present the JpaDAO class

Finally we are going to create the service interface and implementation classes for the GWT client to access. The service interface should be accessible by both the client and the server, so it should be placed under the “shared” subpackage of our project. Create a “services” subpackage and place the service interface there. An example interface class follows

GWT client has to be able to make asynchronous Remote Procedure Calls (RPCs) to the server side service. Thus the service interface must extend the RemoteService interface. An asynchronous counterpart of the specified interface must also be provided to enable asynchronous communication (see below)

We annotate the interface so as to define the URL under which the service will be accessible. As the service is a Spring service we want spring4gwt to intercept the RPC calls and perform a Spring service invocation. To do that we define a relative path that will be handled by “springGwtRemoteServiceServlet” declared in our web.xml as shown above.

The service name declared at “RemoteServiceRelativePath” annotation, here “employeeService”, must match the Spring service bean name. We will define the Spring service bean name in the service implementation class (see below)

The service implementation class is a server side component, so we must place it under “server” subpackage of our project. Create the “services” subpackage and place it there. An example service implementation class is presented below

We use the @Service(“employeeService”) stereotype annotation so as to declare that this class represents a Spring service by the name “exampleService”. The Spring container will instantiate all services at start up.

We use the @Autowire annotation to inject the instance of the DAO class to the “employeeService”. For proper instantiation of the service Spring container has to resolve first all potential references among services, so it instantiates the DAO class and injects the instance to the appropriate field of “employeeService” – the “employeeDAO” field. In case you wonder, the dependency injection is done according to type (Class) and if not satisfied according to name, meaning that if we have defined multiple services of the same type (Class) the one injected would be the one with the same name as the designated field.

We use the Java annotations @PostConstruct and @PreDestroy to declare the methods that will be invoked by Spring container after initialization (all dependency injection is done) and prior destruction of the service.

We use the @Transactional annotation for all methods that need to perform update operation on the database (INSERT, UPDATE, DELETE)

We DO NOT use the @Transactional annotation on methods that perform retrieve (FIND) operations on the database (except for objects that contain lazily initialized references – see below), and/or perform no database operations. That is because every time you invoke a method annotated as transactional, Spring container involves in the invocation JPA‘s entity manager and as a consequence platform’s transaction manager, so as to define the transactional behavior that will be applied, introducing a noticeable performance penalty especially for low latency / high throughput applications

For methods that perform retrieve (FIND) operations for objects that contain lazily initialized references you should use the @Transactional annotation, designating “NESTED” propagation type in order for Spring to maintain Hibernate session open for the entire method call

Transactional behavior is applied only on client calls to the service. Transactional behavior is not applied to intra operation calls. For example if a client invokes an operation that is not annotated as transactional and the implementation of the latter introduces a call to another operation of the same service that is annotated transactional then for the combined operations no transactional behavior will be applied

We are almost done!, we have to develop the GWT user interface to access our Spring service. Despite the fact that GWT user interface development is out of the scope of this tutorial we are going to provide a basic user interface just to show a couple of Spring service invocations.

Locate the entry point of your GWT application. The file should be named like {project_name}.java, in our case GWTSpring.java, and located under “client” subpackage or our main package. Alter the entry point class as shown below

As you can see, Spring service invocations are performed just like classic GWT service invocations, transparently to the client.

Finally locate the main web page for your project. The file should be named like {project_name}.html, in our case GWTSpring.html, and located under /war folder of our project. Alter the main web page as shown below

To compile the application, right click on the project name and select Run As ? Compile GWT Application

To deploy the web application just copy the /war folder in Apache – Tomcat “webapps” folder. You can change the name of the war folder to whatever you like, preferably rename it after the project name e.g. GWTSpring

To launch the application point your browser to the following address

http://localhost:8080/GWTSpring/

If all went well you should see your main web page. Two text boxes should be displayed each followed by a button. In the first text box you can save or update an employee to the database. Provide as input the id, the name, the surname, and a job description separated by a space character. Clicking on the “SaveOrUpdate” button the provided information will be stored to the database. For existing employee entries (same id) an update will be performed. The second text box is used to retrieve existing employee entries. Provide an employee id and click on the “Retrieve” button. If the employee exists you should see the employee id, name, surname and job description.

Few, that was a big tutorial!

You can download the project from here (required 3rd party libraries as described at the beginning are not included)

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial3>

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

10 comments

I am getting the following exception while running the test case for Employee Service. Any help on this is appreciated.

[WARN] com.google.gwt.junit.server.JUnitHostImpl-10213237: An IncompatibleRemoteServiceException was thrown while processing this call.

com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException: This application is out of date, please click the refresh button on your browser. ( Blocked attempt to access interface ‘com.javacodegeeks.SpringGWT.shared.services.EmployeeService’, which is not implemented by ‘com.google.gwt.junit.server.JUnitHostImpl'; this is either misconfiguration or a hack attempt )

at com.google.gwt.user.server.rpc.RPC.decodeRequest(RPC.java:254)

at com.google.gwt.user.server.rpc.HybridServiceServlet.processCall(HybridServiceServlet.java:126)

at com.google.gwt.user.server.rpc.HybridServiceServlet.processCall(HybridServiceServlet.java:113)

at com.google.gwt.rpc.server.RpcServlet.processPost(RpcServlet.java:233)

at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)

Thanks for this good tutorial and full description. It takes two days to get it work for my Configurations. I use a MySQL database and hibernate. My persistence.xml has to be adapted in this way:

And I must add hibernate-validator to /war/lib (classmate-0.8.0.jar,hibernate-validator-5.0.1.Final.jar,javax.el-2.2.4.jar,javax.el-api-2.2.4.jar,jboss-logging-3.1.1.GA.jar,validation-api-1.1.0.Final.jar)!

I downloaded the whole project and inserted the needed libs. Now I keep getting this error: >>> Bean property ‘persistenceUnitName’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

Newsletter

Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

Email address:

Join Us

With 1,043,221 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.