Kevin's Blog

IT, Java, Ubuntu, Linux

Category: Java Web Application Development

Catch-Up 01 May, 2010

Some part of 3. Bug in Java compiler?Shadowing Declarations? is updated twice on the 10th of May in 2010.

I have been very busy and am still busy so haven’t written anything for quite a while on my blog except for those entries with only one or two sentences. So I’m quickly writing what I do these days and some issues I have dealt with.

1. Issue with the new m2eclipse (version: 0.10.0.20100209-0800)

Sonatype released the new version of m2eclipse in February 2010. Since I updated with it, I had got some problem with maven build through Hudson.

The new version of m2eclipse comes with maven3 embedded yet my server uses maven2 so does my Linux on my Desktop PC. So it was only m2eclipse which uses maven3 (SNAPSHOT version) and I deployed some of my libraries used in one web application development project. Problem was that I deployed the dependency libraries several times with the same version number. With maven2, it’s OK as it uses time-stamp to distinguish one version from another within the same version, yet with maven3, having the same version is not allowed. Well, I am not 100% sure about this as once I solved the problem I didn’t really check the details as I didn’t have enough time. Anyway, so as shown in the following image, the project status icon once became dark rain clouds which mean really bad.

Build Failure: Project status icon became dark rain clouds

Build Failure: Project status icon became dark rain clouds

My project build failed seven times due to the difference between maven2 and maven3 I described above, or it can be something else yet it is caused by some difference between those two versions.

Build Failure: It failed seven times due to the difference between maven2 and maven3

Build Failure: It failed seven times due to the difference between maven2 and maven3


(It happened in February. The build number in the image is 108 but it is now 305).

So why did I not just keep the old version of m2eclipse with maven2 embedded? Well, the old one comes with some old version of maven2 which does not support password encryption while the maven2 on both my PC and my server does support it as it is a newer version. Thus I updated with the new m2eclipse as soon as it was available yet didn’t really expect that it comes with maven3. Anyway, It’s solved by using maven2 installed on my PC when deploying project packages. The other times such as solving dependencies and building package without deployment, I can still use the embedded maven3 in the new m2eclipse without any problems.

2. I have been working on…

I founded a start-up company with my friend a few months ago, and we are currently working on a web application development for our own start-up, but it is probably too premature to announce what it is as it’s still an early stage of development.
The issues listed in the following image is a part of the issues I and my colleague have solved and been working on.

I'm currently working on this project.

I'm currently working on this project.

In addition, I have been developing my own Java libraries which can be commonly used in many other projects (and my friend has also been developing reusable JavaScript libraries). However, I did not record all the issues belong to these reusable components and recently felt that I should do it before I go any further. Otherwise, I may later forget what problems I solved and how I did as well as all the issues covered previously. So I wrote all the tickets for those libraries.

Issues of commonly used libraries built by myself

Issues of commonly used libraries built by myself

I’ve also been developing ‘Java object to JSON’ library and did the same as what I just explained (that is creating issue tickets). There are already a number of the libraries which convert Java object into JSON so why would I make another? Well, there can be several reasons but major ones are

  1. I need it to convert any POJO with only annotations into JSON.
  2. It has to be simple as I do not want to have any complex functions or heavy library for a simple conversion (some libraries are too heavy for such a simple task).
  3. When customisation is required or bug is found in the library, I want to be able to change and fix it however I want so that I do not have to waste my time on waiting for others to solve it.
  4. I want it to work in some environments where using bytecode manipulation is not an option. So if I programme one with bytecode manipulation then it works faster when it’s available whereas the other one is without it so that it can be used in those enviornments (I currently have only the latter one and will do the former one when I have time later).

The following issues are what I have solved for the Java to JSON library.

Issues of my Java object to JSON library

Issues of my Java object to JSON library

Finally, I have another project to help Ajax enabled web application development. From my experience, I found that it is sharing the information about the available server-side functions with the client-side developers that causes the most waste of time between the front-end development and the back-end development. The first time one function is made or whenever the existing ones are changed, I have to write or rewrite the document explaining it and the client-side developer has to find the changed parts in the document. It is annoying and a non-productive moment in the development so I and my colleague discussed about this issue and came up with the idea of having a library which exposes all the available server-side functions to the front-end (It can understand Spring @MVC controllers). For now, it has only this, yet I will add more features to help Ajax web application development.

Issues of my web method library

Issues of my web method library

* As I used more and more reflection to develop those libraries, I realised that Java Reflection has no method to get the names of method parameters. Well, there can be some ways for instance, using -g (generating debugging info) option when compiling or using some libraries such as ASM or use ParaNamer (It requires an additional step when compiling to add the constants having the parameter names in the class) but not by just Java reflection. Anyway, none of these is the solution I want, and unfortunately if I heard right, this problem will remain in JDK 7. :(

3. Bug in Java compiler? Shadowing Declarations?

I created the Objects utility class based on http://download.java.net/jdk7/docs/api/java/util/Objects.html. This will be available in JDK 7 yet I wanted to use it before JDK 7 is released so I made my own one. I can use it now, and it can easily be replaced by the one in JDK when it’s available. After I made it, I found some weird bug, I believe, in Java compiler. After I used it, I had some problem and thought it could be a bug in Java compiler yet it looks like ‘shadowing declarations’.

This is the part of Objects class I coded.

package com.lckymn.kevin.common.util;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public final class Objects
{
    private Objects()
    {
        throw new IllegalStateException(getClass().getName() + " cannot be instantiated.");
    }

    // other code omitted ...

    /**
     * Returns the hash code of a non-{@code null} argument and 0 for a {@code null} argument.
     * 
     * @param o
     *            an object
     * @return the hash code of a non-{@code null} argument and 0 for a {@code null} argument
     * @see {@link Object#hashCode()}
     */
    public static int hashCode(final Object o)
    {
        return (null == o ? 0 : o.hashCode());
    }

    // other code omitted ...
}

The following code is a POJO in which I want to use the Objects.hashCode(Object) method.

package com.lckymn.kevin.test.bean;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public class SomePojo
{
    private final int number;
    private final String name;

    public SomePojo(int number, String name)
    {
        this.number = number;
        this.name = name;
    }

    public int getNumber()
    {
        return number;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (!(obj instanceof SomePojo))
        {
            return false;
        }
        final SomePojo that = (SomePojo) obj;
        return (this.number == that.getNumber())
                && (this.name == that.getName() || 
                        (null != this.name && this.name.equals(that.getName())));
    }
}

So I changed this code snippet

@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    result = prime * result + number;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}

to this.

package com.lckymn.kevin.test.bean;

import static com.lckymn.kevin.common.util.Objects.*;

public class SomePojo
{
    // ...

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + hashCode(name);
        return result;
    }
}

I used static import and hashCode(Object) method in the Objects class. Although, nothing’s wrong in the code, my Eclipse complains that there is a compile-time error. The following image shows that.

Objects.hashCode(Object) with static import does not work.

Objects.hashCode(Object) with static import does not work.

Yet the same code with no-static import but using class name as the qualifier to use hashCode(Object) method works perfectly. The following code has Objects.hashCode(name) and no compile-time error.

package com.lckymn.kevin.test.bean;

import com.lckymn.kevin.common.util.Objects;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public class SomePojo
{
    private final int number;
    private final String name;

    public SomePojo(int number, String name)
    {
        this.number = number;
        this.name = name;
    }

    public int getNumber()
    {
        return number;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + Objects.hashCode(name);
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (null == obj)
        {
            return false;
        }
        if (!(obj instanceof SomePojo))
        {
            return false;
        }
        final SomePojo that = (SomePojo) obj;
        return (this.number == that.getNumber())
                && (this.name == that.getName() || (null != this.name && this.name.equals(that.getName())));
    }
}

The following image shows it has no error in the part where Objects.hashCode(Object) is used..

Using Class as qualifier to use hashCode works.

Using Class as qualifier to use hashCode works.

I wondered if it’s a bug in the Eclipse or a bug in the Java compiler. So I opened the terminal and tested it.

$ javac -version
javac 1.6.0_15


$ javac com/lckymn/kevin/test/bean/SomePojo.java
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : <nulltype>
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors

As it shows, the compiler does totally not understand that the hashCode(Object) method from the Objects class is available and valid.

Is a bug only in the SUN JDK in the Ubuntu Linux repository? So I tried with OpenJDK 6 as well.

$ /usr/lib/jvm/java-6-openjdk/bin/javac -version
javac 1.6.0_0

$ /usr/lib/jvm/java-6-openjdk/bin/javac com/lckymn/kevin/test/bean/SomePojo.java 
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : <nulltype>
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors

The same result…

OK, it might be a bug in that particular version. Fortunately, the most recent version of SUN JDK 6 was released yesterday. It was officially released before (the 15th of April, 2010) yet the version managed by Ubuntu was not available before yesterday. So I installed it and tested it again with the Java compiler in the new JDK6.

New version of SUN JDK6 is available in the Ubuntu repository

New version of SUN JDK6 is available in the Ubuntu repository

It still has the same problem.

$ javac -version
javac 1.6.0_20

$ javac com/lckymn/kevin/test/bean/SomePojo.java
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : <nulltype>
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors

I probably need to test with the Java compiler in the JDK6 for Windows but I have no stomach for that now nor do I have time to do that.

* Update1 (2010-05-10)
I also tested it with the Java compiler in the JDK 6 (1.6.0_16) for Windows and got the same result. It seem like static import cannot handle method overloading. I didn’t have time to research to find the details but based on my testing, method overloading cannot be used with static import.
If so then there should be a good reason for that, and the only one I can think of right now is that it might have something to do with varargs.

Take a look at the following code.

package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + " cannot be instantiated.");
    }
    
    public static void test(Object... object)
    {
        System.out.println("SomeHelper.test()");
    }
}
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test()
    {
        System.out.println("Test.test()");
    }

    public void callTest()
    {
        test();            // no error here.

        Object object = new Object();
        test(object);    // compile-time error
    }
}

Since a method with varargs can take no argument when it’s called, Test.test() and SomeHelper.test(Object… object) can be indistinguishable with static import. This is, I think, probably one of the reasons why method overloading is not allowed with static import. Nevertheless, it is still very weird as calling test() does not cause any compile-time error while test(object) does.
So the following code has no compile-time error and displays Test.test().

package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test()
    {
        System.out.println("Test.test()");
    }

    public void callTest()
    {
        test();    // static import of SomeHelper.test has no effect here.
    }
    
    public static void main(String[] args)
    {
        new Test().callTest();
        System.exit(0);
    }
}

It displays Test.test().

What if the helper class has test() method with no arguments and the Test class has test() method with varargs then call test()? The same result! It still calls Test’s test() method with varargs (Test.test(Object... object)).

package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + " cannot be instantiated.");
    }
    
    public static void test()
    {
        System.out.println("SomeHelper.test()");
    }
}
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test(Object... object)
    {
        System.out.println("Test.test(Object...object)");
    }

    public void callTest()
    {
        test(); // it calls the Test.test(Object... object) method NOT SomeHelper.test().
    }

    public static void main(String[] args)
    {
        new Test().callTest();
        System.exit(0);
    }
}

It displays Test.test(Object...object)

Update2 (2010-05-10)
It is more likely to be ‘Shadowing Declarations’. Although, I couldn’t find the exactly matching case from the JLS yet, it makes more sense if the method imported by static-import is shadowed.

4. Using Objects

By the way, the Objects class is simple but very useful.
with it, the highlighted parts of the following code can

package com.lckymn.kevin.test.bean;

public class Bank
{
    private Long id;
    private String bankName;
    private String bsbNumber;
    private String address;

    public Long getId()
    {
        return id;
    }

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

    public String getBankName()
    {
        return bankName;
    }

    public void setBankName(String bankName)
    {
        this.bankName = bankName;
    }

    public String getBsbNumber()
    {
        return bsbNumber;
    }

    public void setBsbNumber(String bsbNumber)
    {
        this.bsbNumber = bsbNumber;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((bankName == null) ? 0 : bankName.hashCode());
        result = prime * result + ((bsbNumber == null) ? 0 : bsbNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object bank)
    {
        if (this == bank)
        {
            return true;
        }
        if (!(bank instanceof Bank))
        {
            return false;
        }
        final Bank that = (Bank) bank;
        return (this.bankName == that.getBankName() || 
               (null != this.bankName && this.bankName.equals(that.getBankName())))
                && (this.bsbNumber == that.getBsbNumber() || 
                   (null != this.bsbNumber && this.bsbNumber.equals(that.getBsbNumber())));
    }
}

become like this

package com.lckymn.kevin.test.bean;

import com.lckymn.kevin.common.util.Objects;

public class Bank
{
    private Long id;
    private String bankName;
    private String bsbNumber;
    private String address;

    public Long getId()
    {
        return id;
    }

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

    public String getBankName()
    {
        return bankName;
    }

    public void setBankName(String bankName)
    {
        this.bankName = bankName;
    }

    public String getBsbNumber()
    {
        return bsbNumber;
    }

    public void setBsbNumber(String bsbNumber)
    {
        this.bsbNumber = bsbNumber;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(bankName, bankName);
    }

    @Override
    public boolean equals(Object bank)
    {
        if (this == bank)
        {
            return true;
        }
        if (!(bank instanceof Bank))
        {
            return false;
        }
        final Bank that = (Bank) bank;
        return Objects.equals(this.bankName, that.getBankName()) 
               && Objects.equals(this.bsbNumber, that.getBsbNumber());
    }
}

So these five lines in the hashCode method

final int prime = 31;
int result = 1;
result = prime * result + ((bankName == null) ? 0 : bankName.hashCode());
result = prime * result + ((bsbNumber == null) ? 0 : bsbNumber.hashCode());
return result;

become

return Objects.hash(bankName, bankName);

and these four lines in the equals method

return (this.bankName == that.getBankName() || 
       (null != this.bankName && this.bankName.equals(that.getBankName())))
        && (this.bsbNumber == that.getBsbNumber() || 
           (null != this.bsbNumber && this.bsbNumber.equals(that.getBsbNumber())));

become

return Objects.equals(this.bankName, that.getBankName()) 
       && Objects.equals(this.bsbNumber, that.getBsbNumber());

Although one might say that I can use Lombok instead, I prefer to see what is going on in my code. Those hashCode and equals methods are not additional info of the class. It tells what makes instances of the class equal thus I prefer to have it in there to see and want to freely change it whenever and however I want. Well, in other words, just a matter of personal preference. :)
That’s it.
I perhaps have more to say yet am getting tired (4:55 AM :O). So I’m calling it a night. :)

Web Service Development using Tomcat and OpenEJB

In addition to the previous post, Java EE Application Development using Tomcat, OpenEJB and Hibernate, this post will demonstrate how to create a web service using Tomcat and OpenEJB. The web service in this blog entry uses the code from the previous post, so if you haven’t read it yet, better read it first.

Firstly, create a web service interface then put the @WebService annotation.

package com.lckymn.kevin.test.openejb.webservice;

import javax.jws.WebService;

import com.lckymn.kevin.test.openejb.domain.User;

@WebService
public interface TestWebService
{
	User getUser(Long id);
}

Secondly, create a class implmenting the web service interface with also the @WebService annotation then specify the targetNamespace and the serviceName as you wish. In my case, these are

targetNamespace: "http://webservice.webhibernate.test"
serviceName: "testWebService"

To use the UserService EJB, injected by OpenEJB, make the web service class session EJB with the @Stateless annotation.

package com.lckymn.kevin.test.openejb.webservice;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.jws.WebService;

import com.lckymn.kevin.test.openejb.domain.User;
import com.lckymn.kevin.test.openejb.service.UserService;

@Local
@Stateless
@WebService(targetNamespace = "http://webservice.webhibernate.test", serviceName = "testWebService")
public class TestWebServiceImpl implements TestWebService
{
	@EJB
	private UserService userService;

	@Override
	public User getUser(Long id)
	{
		return userService.getUser(id);
	}
}

The class above simply returns a User entity object acquired from the UserService EJB, made in the previous post.

That’s it. You have just made your web service. When the server starts and the application is deployed, the EJB container (OpenEJB) registers the above EJB as a web service.

Now, let’s make a web service client. To make a very simple example client, I’m going to create a servlet in the same web application to which the web service belongs, yet it can of course be another web application, Java desktop application, Java console application and so on.

Here is a simple servlet which gets the user ID from the client-side then accesses the web service to get the User. After that it passes the User entity object through the HttpSession to the JSP page to display.

package com.lckymn.kevin.test.openejb.web;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.lckymn.kevin.test.openejb.domain.User;
import com.lckymn.kevin.test.openejb.webservice.TestWebService;

public class TestWebServiceClientServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		Service service = Service.create(new URL("http://localhost:8080/TestWebServiceImpl?wsdl"), new QName(
				"http://webservice.webhibernate.test", "testWebService"));
		TestWebService testWebService = service.getPort(TestWebService.class);

		String userIdParam = request.getParameter("userId");

		HttpSession session = request.getSession();
		if (null == userIdParam || 0 == userIdParam.length())
		{
			session.removeAttribute("userFound");
		}
		else
		{
			Long userId = Long.parseLong(userIdParam);
			User user = testWebService.getUser(userId);
			session.setAttribute("userFound", user);
		}
		getServletContext().getRequestDispatcher("/WEB-INF/jsp/webServiceClient.jsp")
				.forward(request, response);
	}
}

This is just a simple example thus I omitted validation (e.g. checking whether the userId is ‘long’ type or not) and exception handling.

The WSDL location is the server URI + “/” + web service class name + “?wsdl”.
http://localhost:8080/TestWebServiceImpl?wsdl
The parameters of the QName constructor are namespaceURI and localPart, and these are defined in the web service. If you look at the web service code again, these can easily be found from the @WebService annotation.

@WebService(targetNamespace = "http://webservice.webhibernate.test", serviceName = "testWebService")
public class TestWebServiceImpl implements TestWebService
{
	...
}

The value of the targetNamespace element is the namespaceURI of the QName constructor, and the value of the serviceNmae element is the localPart.

This is web.xml. The information of the new servlet, the web service client just created, is added to the web.xml, made in the previous post.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>test-web-hibernate</display-name>
  <servlet>
    <description></description>
    <display-name>TestServlet</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.lckymn.kevin.test.openejb.web.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/Test</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>TestWebServiceClientServlet</display-name>
    <servlet-name>TestWebServiceClientServlet</servlet-name>
    <servlet-class>com.lckymn.kevin.test.openejb.web.TestWebServiceClientServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestWebServiceClientServlet</servlet-name>
    <url-pattern>/TestWebServiceClient</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Finally, add a JSP file to enter the userId to search a user and to display the user info.
In my case, I added the file to the application/WebContent/WEB-INF/jsp directory which is the same location that I set in the TestWebServiceClientServlet (look at the TestWebServiceClientServlet code above).
test-web-hibernate/WebContent/WEB-INF/jsp/webServiceClient.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<div>
<form name="userForm" action="TestWebServiceClient" method="post" >
	<input type="text" name="userId" value="" /> <input type="submit" name="userIdSubmit" value="Search" />
</form>
</div>
<div>
	<table>
		<tr>
			<td>User ID: </td><td>${userFound.id }</td>
		</tr>
		<tr>
			<td>Username: </td><td>${userFound.username }</td>
		</tr>
		<tr>
			<td>Surname: </td><td>${userFound.surname }</td>
		</tr>
		<tr>
			<td>Given name: </td><td>${userFound.givenName }</td>
		</tr>
		<tr>
			<td>Email: </td><td>${userFound.email }</td>
		</tr>
	</table>
</div>
</body>
</html>

To test it, open the browser and enter the following URI.


http://localhost:8080/test-web-hibernate/TestWebServiceClient

It displays the screen like below

Enter userId and click the 'Search' button

Enter userId and click the 'Search' button


-Enter a userId to search then click the ‘Search’ button.

It displays the result yet there is one problem. It doesn’t display the userId.

The Search Result: userId is not displayed

The Search Result: userId is not displayed


This is because the id field of the User entity class that I created in the previous blog entry does not have the mutator that is the setId() method so when the entity object is passed through the web service, the id field is not included.

There are two simple ways to solve this problem. Either way works so choose whichever you like.

1. Add the setter method. If there is setId() method, the id field is included when the object is passed through the web service. The reason why I did not write the setter method is that the id is supposed to be set by Hibernate and to avoid any problems caused by setting it manually, I did not write it. However, it is required in order to include the field when passing object through the web service. So adding setter can solve this problem. If you do not like this solution as you do not like to put the setter method due to the reason I explained, you can try the second solution.

@Entity
@Table(name = "users")
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "user_id")
	private Long id;

	...

	public Long getId()
	{
		return id;
	}

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

OR

2. If you add the @XmlElement annotation to the id field and set the value of the required element to true, the id field is included even without the setter method.

...

import javax.xml.bind.annotation.XmlElement;

...
@Entity
@Table(name = "users")
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "user_id")
	@XmlElement(required = true)
	private Long id;

	...

	public Long getId()
	{
		return id;
	}

	// No setId() required
	
	...
}

Now, test if it works.

Enter userId and click the 'Search' button

Enter userId and click the 'Search' button

It works!

The Search Result: userId is displayed correctly

The Search Result: userId is displayed correctly

There are also other ways and tools to create a web service in Java. I used to use Apache Axis then later moved to XFire. Now, I use Apache CXF which is considered as XFire 2.0. It is, as explained here, very easy to create a web service client, yet it can be even easier with WSDL2Java from Apache Axis or WSDL2Java from Apache Axis2.

Java EE Application Development using Tomcat, OpenEJB and Hibernate

Java EE Application Development using Tomcat, OpenEJB and Hibernate

Before I start writing this blog entry, I’d better point out a few things.

  • This blog entry is not about how to make a good Java EE application yet is about how to use OpenEJB on Apache Tomcat server with Hibernate as an implementation of the JPA. If you are looking for better Java EE development or similar, this one is not for you. :)
  • I don’t have enough time to explain all the details of how to install JDK, Eclipse, Tomcat and so on. So this post doesn’t have that level of details. I simply assume that you’ve already known how to install JDK, Eclipse and Tomcat. Well, anyway, installing Eclipse and Tomcat are as easy as extracting a zip or gzip file and JDK installation is also not difficult at all.
  • This post does not cover how to use those tools and frameworks in the production environment. In other words, it is only for the development. Setting up the environment for development and for the production use have some differences. It is, however not that hard to figure out once you know how to use those in your development environment.

1. Development Environment

First of all, I’m going to list the development environment and tools I have for this introductory tutorial post.
(Click each name and it will take you to the download page).

OS: Ubuntu Linux Jaunty Jackalope 9.04 Desktop 64bit
Java: Sun JDK 1.6.0_16 (64 bit) (it’s from the Ubuntu repository).
Database: MySQL Community Server 5.0 (it’s from the Ubuntu repository).
JDBC Driver: MySQL Connector/J 5.1.10
Eclipse: Eclipse IDE for Java EE Developer Ganymede SR2 (Eclipse 3.4.2)
Tomcat: Tomcat 6.0.20
OpenEJB: OpenEJB 3.1.1 (openejb.war)
Hibernate: Hibernate 3.2.1GA (including hibernate-3.2.1.ga, hibernate-annotations-3.2.1.ga, hibernate-entitymanager-3.2.1.ga) (OR just >>download this<<)

2. Installing OpenEJB

Java EE server normally means a Java application server which consists of a Servlet container and an EJB container. Apache Tomcat is a servlet container but not an EJB container so you need to have an EJB container like OpenEJB or use a Java EE server instead of Tomcat in order to use EJB unless you’re using the frameworks supporting EJB such as Spring framework. “So if I use Tomcat server and Spring framework, do I not need OpenEJB or other Java EE servers to use EJB?” No, you don’t.

Since this post is, as already mentioned, about using using EJB on Tomcat with OpenEJB and Hibernate, I will first show you how to install OpenEJB.

Before installing OpenEJB, don’t forget to copy JDBC driver that is, in this post, MySQL Connector/J to the $TOMCAT/lib directory.
-Copy the Connector/J jar file to the Tomcat’s library directory ($TOMCAT_HOME/lib)

Select Connector/J and Extract to the $TOMCAT/lib directory.

Select Connector/J and Extract to the $TOMCAT/lib directory.

Make sure the Connector/J jar file is in the $TOMCAT/lib directory.

Make sure the Connector/J jar file is in the $TOMCAT/lib directory.

-Run Eclipse and add Tomcat server: Menu – Window -> Preferences -> Server -> Runtime Environments -> Add

-Download the openejb.war, OpenEJB for Tomcat, and import the file from Eclipse.
-Right click on the project explorer -> Import -> WAR file

Right Click on the project explorer -> Import -> WAR File

Right Click on the project explorer -> Import -> WAR File

-Click the ‘Browse’ button and select the openejb.war file -> Select your Tomcat 6.0 as the target runtime. -> Click the ‘Finish’ button.

Click the 'Browse' button and select the openejb.war file -> Select your Tomcat 6.0 as the target runtime. -> Click the 'Finish' button.

Click the 'Browse' button and select the openejb.war file -> Select your Tomcat 6.0 as the target runtime. -> Click the 'Finish' button.

3. Add OpenEJB project to the Server to deploy

-Right click on the server name in the ‘Server’ view -> Select the ‘Add and Remove Projects…’

Right click on the server name in the 'Server' view -> Select the 'Add and Remove Projects...'

Right click on the server name in the 'Server' view -> Select the 'Add and Remove Projects...'

-Select openejb -> Click the ‘Add’ button -> Click the ‘Finish’ button

Select openejb -> Click the 'Add' button -> Click the 'Finish' button

Select openejb -> Click the 'Add' button -> Click the 'Finish' button

-openejb is ready to be deployed.

openejb is deployed.

openejb is deployed.

-Now run the server to deploy openejb.

Run the server to deploy openejb

Run the server to deploy openejb

-openejb is successfully deployed.

the openejb is successfully deployed.

the openejb is successfully deployed.

4. Set up DataSource

-openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace.

openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace.

openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace.

If you are using Tomcat without OpenEJB and want to create a DataSource, you might do by putting the DataSource info to Tomcat’s server.xml file or your application’s context configuration file (your_app/META-INF/context.xml). Yet to create the DataSource for JPA, you need to do through openejb.xml file. It is created in the Tomcat folder in the .metadata folder of your Eclipse workspace when the openejb project is deployed. However, it is not copied automatically to the configuration folder of your Eclipse workspace, you should copy the openejb.xml file to the Server configuration folder manually. If the location of the workspace is ‘/home/username/workspace’, the Tomcat is in ‘/home/username/test-workspace/.metadata/.plugins/org.eclipse.wst.server.core’ and the openejb.xml file can be found in the ‘/home/username/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf’ directory.

-Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace.

Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace.

Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace.


Paste the file to the Tomcat configuration folder of the Eclipse workspace.

Paste the file to the Tomcat configuration folder of the Eclipse workspace.

-Open the ‘openejb.xml’ file then you can find the default DataSources.

Open the 'openejb.xml' file then you can find the default DataSources

Open the 'openejb.xml' file then you can find the default DataSources


One is JTA managed while the other is not. Both use HSQLDB which is a Java database. If you don’t have any database installed on you computer or if you want, you can use it. As mentioned early, I am going to use MySQL so a new data source set up for MySQL is required.

-Add the following lines and modify for your own database.

<Resource id="mysqlDataSource" type="javax.sql.DataSource">
	JdbcDriver      	com.mysql.jdbc.Driver
	JdbcUrl         	jdbc:mysql://localhost:3306/test_db
	UserName        	test_user
	Password        	1234
	JtaManaged      	true
	DefaultAutoCommit 	true
	InitialSize     	3
	MaxActive       	20
	MinIdle         	20
	MaxIdle         	0
	MaxWait         	50000
	ValidationQuery 	SELECT 1
	TestOnBorrow    	true
	TestOnReturn    	false
	TestWhileIdle   	false
</Resource>
DataSource to access the MySQL database.

DataSource to access the MySQL database.

If you want to use OpenJPA as an implmentation of the JPA, you can do now. However, to use Hibernate there is one more step to do.

5. Install Hibernate

If you just have the Hibernate jar files in your application directory (e.g. your_app/WEB-INF/lib), the EJB container that is OpenEJB cannot find the hibernate classes as it is the container, it tries to find the hibernate class from the server’s lib directory. Thus just like you need to copy the JDBC driver, in this post it’s ‘Connector/J’, to the tomcat’s lib directory, the hibernate jar files should be placed in the Tomcat’s lib directory.

Otherwise, you will get an error like this.

ERROR - Unable to deploy collapsed ear in war /test-web-hibernate: Exception: Creating application failed: /home/username/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/test-web-hibernate: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence: org.hibernate.ejb.HibernatePersistence
org.apache.openejb.OpenEJBException: Creating application failed: /home/username/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/test-web-hibernate: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence: org.hibernate.ejb.HibernatePersistence
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:658)
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:442)
	at org.apache.openejb.tomcat.catalina.TomcatWebAppBuilder.start(TomcatWebAppBuilder.java:249)
	at org.apache.openejb.tomcat.catalina.GlobalListenerSupport.lifecycleEvent(GlobalListenerSupport.java:58)
	at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
	at org.apache.catalina.core.StandardContext.start(StandardContext.java:4339)
	at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3190)
	at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:404)
	at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1309)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1601)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1610)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1610)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1590)
	at java.lang.Thread.run(Thread.java:619)
Caused by: org.apache.openejb.OpenEJBException: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence: org.hibernate.ejb.HibernatePersistence
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:487)
	... 13 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
	at org.apache.openejb.assembler.classic.PersistenceBuilder.createEntityManagerFactory(PersistenceBuilder.java:177)
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:482)
	... 13 more
So you have to copy the hibernate to the Tomcat’s lib directory. Unfortunately, the latest version of Hibernate (3.4.0GA) does not work on OpenEJB 3.1.1 yet I found the 3.2.1GA version works. However, there is another problem. When you try to use Tomcat, OpenEJB and Hibernate, it may not work well with the dependency libraries required by Hibernate 3.2.1GA so you should carefully choose the dependency files. This means you need to test and find which ones are working well with OpenEJB and which are not. Fortunately, here is a good news. I tested and found the files working well with Tomcat 6 and OpenEJB and zipped the files. Thus you can simply download this file and extract it to the $TOMCAT/lib directory.

Click Here to Download the File!

After downloading, extract all the files inside to the Tomcat’s lib directory ($TOMCAT/lib) just like what you did to install JDBC driver, Connector/J.

6. Adding logger configuration (Optional)

By default, OpenEJB creates a log file in the Eclipse’s $TOMCAT/logs directory. It is very inconvenient as you have to open the file when you want to get information from the log. However, it is very easy to change this to make it displayed on the Console view of Eclipse.

-Right click on the Tomcat configuration folder -> Select ‘New’ -> Select ‘File’ -> crated a file with the name ‘logging.properties’.

Right click on the Tomcat configuration folder -> Select 'New' -> Select 'File' -> crated a file with the name 'logging.properties'.

Right click on the Tomcat configuration folder -> Select 'New' -> Select 'File' -> crated a file with the name 'logging.properties'.

-Open the file and put the following lines

log4j.rootLogger                   = fatal,C
log4j.category.OpenEJB             = warn
log4j.category.OpenEJB.options     = info
log4j.category.OpenEJB.server      = info
log4j.category.OpenEJB.startup     = info
log4j.category.OpenEJB.startup.service = warn
log4j.category.OpenEJB.startup.config = info
log4j.category.OpenEJB.hsql        = info
log4j.category.CORBA-Adapter       = info
log4j.category.Transaction         = warn
log4j.category.org.apache.activemq = error
log4j.category.org.apache.geronimo = error
log4j.category.openjpa             = error

log4j.appender.C                   = org.apache.log4j.ConsoleAppender
log4j.appender.C.layout            = org.apache.log4j.SimpleLayout
Put the logger config details

Put the logger config details

7. Create Web Application Project

Now, you can develop a web application using EJB3 and Hibernate as the implementation of the JPA.

-Right click on the project explorer -> Select ‘New’ -> Select ‘Dynamic Web Project’

Right click on the project explorer -> Select 'New' -> Select 'Dynamic Web Project'

Right click on the project explorer -> Select 'New' -> Select 'Dynamic Web Project'

-Put the name you like -> Select the ‘Apache Tomcat v6.0′ as the target runtime -> Select ’2.5′ as the version of ‘Dynamic Web Module’ -> Select the default Tomcat configuration or your own one -> Click the ‘Next’ button.

Put the name you like -> Select the 'Apache Tomcat v6.0' as the target runtime -> Select '2.5' as the version of 'Dynamic Web Module' -> Select the default Tomcat configuration or your own one -> Click the 'Next' button.

Put the name you like -> Select the 'Apache Tomcat v6.0' as the target runtime -> Select '2.5' as the version of 'Dynamic Web Module' -> Select the default Tomcat configuration or your own one -> Click the 'Next' button.

-Change the project context root and directory names if you like -> Click the ‘Finish’ button.

Change the project context root and directory names if you like -> Click the 'Finish' button.

Change the project context root and directory names if you like -> Click the 'Finish' button.

-Right click on the Server to add the project -> Select the ‘Add and Remove Projects…’.

Right click on the Server to add the project -> Select the 'Add and Remove Projects...'.

Right click on the Server to add the project -> Select the 'Add and Remove Projects...'.

-Select the project you created -> Click the ‘Add’ button -> Click the ‘Finish’ button.

Select the project you created -> Click the 'Add' button -> Click the 'Finish' button.

Select the project you created -> Click the 'Add' button -> Click the 'Finish' button.

-Both openejb and your project are added.

Both openejb and your project are added.

Both openejb and your project are added.

8. Make JPA Project

To use the JPA support feature of Eclipse, you need to change the project facet configuration.

-Right click on your project -> Select the ‘Properties’.

Right click on your project -> Select the 'Properties'.

Right click on your project -> Select the 'Properties'.

-Select the ‘Project Facets’ -> Check ‘Java Persistence 1.0′ -> Click the ‘Further configuration available…’ link.

Select the 'Project Facets' -> Check 'Java Persistence 1.0' -> Click the 'Further configuration available...' link.

Select the 'Project Facets' -> Check 'Java Persistence 1.0' -> Click the 'Further configuration available...' link.

-Select ‘Generic’ -> Select ‘None’ or your own connection or add a new connection if you wish -> Select ‘Use implementation provided by server runtime’ -> Select ‘Discover annotated classes automatically’ -> Uncheck ‘Create orm.xml’ option -> Click the ‘OK’ button.

Select 'Generic' -> Select 'None' or your own connection or add a new connection if you wish -> Select 'Use implementation provided by server runtime' -> Select 'Discover annotated classes automatically' -> Uncheck 'Create orm.xml' option -> Click the 'OK' button.

Select 'Generic' -> Select 'None' or your own connection or add a new connection if you wish -> Select 'Use implementation provided by server runtime' -> Select 'Discover annotated classes automatically' -> Uncheck 'Create orm.xml' option -> Click the 'OK' button.


(I do usually not set up the connection yet if you want to generate entity classes from the existing tables, you’d better set it up).

9. Add Java EE 5 API library file

You also need to add the Java EE 5 API library file so you can use all the necessary annotations required for EJB3 and JPA.

-Select ‘Java Build Path on the left-hand side menu -> Select the ‘Libraries’ tab -> Click the ‘Add JARs…’ button.

Select 'Java Build Path on the left-hand side menu -> Select the 'Libraries' tab -> Click the 'Add JARs...' button.

Select 'Java Build Path on the left-hand side menu -> Select the 'Libraries' tab -> Click the 'Add JARs...' button.

-Select ‘javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -> Click the ‘OK’ button.

Select 'javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -> Click the 'OK' button.

Select 'javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -> Click the 'OK' button.

-Click the ‘OK’ button.

Click the 'OK' button.

Click the 'OK' button.


-JPA configuration file (persistence.xml) is added.
JPA configuration file (persistence.xml) is added

JPA configuration file (persistence.xml) is added

10. Configure persistence.xml file

It’s the last step before starting to programme the actual application.

-Open the persistence.xml file -> Type ‘org.hibernate.ejb.HibernatePersistence’ to the ‘Persistence Provider’.

org.hibernate.ejb.HibernatePersistence
Open the persistence.xml file -> put 'org.hibernate.ejb.HibernatePersistence' to the 'Persistence Provider'.

Open the persistence.xml file -> put 'org.hibernate.ejb.HibernatePersistence' to the 'Persistence Provider'.

-Click the ‘Connection’ tab -> Select the ‘JTA’ as the ‘Transaction Type’ -> Type ‘mysqlDataSource’ or your datasource name added in the previous steps. -> Press ‘Ctrl + S’ keys to save the file.

Click the 'Connection' tab -> Select the 'JTA' as the 'Transaction Type' -> Type 'mysqlDataSource' or your datasource name added in the previous steps. -> Press 'Ctrl + S' keys to save the file.

Click the 'Connection' tab -> Select the 'JTA' as the 'Transaction Type' -> Type 'mysqlDataSource' or your datasource name added in the previous steps. -> Press 'Ctrl + S' keys to save the file.

-If you select the ‘Source’ tab, you should see the XML like this.

If you select the 'Source' tab, you should see the XML like above.

If you select the 'Source' tab, you should see the XML like above.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
	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_1_0.xsd">
	<persistence-unit name="test-web-hibernate" transaction-type="JTA">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<jta-data-source>mysqlDataSource</jta-data-source>
	</persistence-unit>
</persistence>

-If you want Hibernate to automatically create the database tables based on your entity classes every time the server is restarted (in other words, the application is re-deployed), You can add Hibernate specific properties.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
	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_1_0.xsd">
	<persistence-unit name="test-web-hibernate" transaction-type="JTA">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<jta-data-source>mysqlDataSource</jta-data-source>
		<properties>
			<property name="hibernate.hbm2ddl.auto" value="create" />
		</properties>
	</persistence-unit>
</persistence>

11. Test

Finally, we have the development environment ready. To test, if I can use EJB3 and JPA with Hibernate on Tomcat, I made a very simple application. The way I design it is not my usual way yet I used Generic DAO pattern which I usually use.

11.1. Entity classes

Here is my only entity class in this test.

package com.lckymn.kevin.test.openejb.domain;

import java.io.Serializable;

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

@Entity
@Table(name = "users")
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "user_id")
	private Long id;

	@Column(name = "username", nullable = false, length = 30)
	private String username;

	@Column(name = "surname", nullable = false, length = 50)
	private String surname;

	@Column(name = "given_name", nullable = false, length = 50)
	private String givenName;

	@Column(name = "email", nullable = true, length = 255)
	private String email;

	public Long getId()
	{
		return id;
	}

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public String getSurname()
	{
		return surname;
	}

	public void setSurname(String surname)
	{
		this.surname = surname;
	}

	public String getGivenName()
	{
		return givenName;
	}

	public void setGivenName(String givenName)
	{
		this.givenName = givenName;
	}

	public String getEmail()
	{
		return email;
	}

	public void setEmail(String email)
	{
		this.email = email;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}

		if (!(obj instanceof User))
		{
			return false;
		}
		User that = (User) obj;
		return (username == that.getUsername() || (null != username && username.equals(that.getUsername())));
	}

	@Override
	public int hashCode()
	{
		return (null == username ? 0 : username.hashCode());
	}
}

11.2. Generic DAOs

package com.lckymn.kevin.test.openejb.dao;

public interface GenericDao<E, K>
{
	E find(K id);

	void persist(E e);

	void remove(E e);
}
package com.lckymn.kevin.test.openejb.dao;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public abstract class AbstractGenericDao<E, K> implements GenericDao<E, K>
{
	private Class<E> classType;

	@PersistenceContext(unitName = "test-web-hibernate")
	private EntityManager entityManager;

	@SuppressWarnings("unchecked")
	public AbstractGenericDao()
	{
		ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
		classType = (Class<E>) parameterizedType.getActualTypeArguments()[0];
	}

	protected final EntityManager getEntityManager()
	{
		if (null == entityManager)
		{
			throw new IllegalStateException("EntityManager is not injected.");
		}
		return entityManager;
	}

	@Override
	public E find(K id)
	{
		return getEntityManager().find(classType, id);
	}

	@Override
	public void persist(E e)
	{
		getEntityManager().persist(e);
	}

	@Override
	public void remove(E e)
	{
		getEntityManager().remove(e);
	}
}
package com.lckymn.kevin.test.openejb.dao;

import java.util.List;

import javax.ejb.Local;

import com.lckymn.kevin.test.openejb.domain.User;

@Local
public interface UserDao extends GenericDao<User, Long>
{
	List<User> getUsersByGivenName(String givenName);
}
package com.lckymn.kevin.test.openejb.dao;

import java.util.List;

import javax.ejb.Stateless;

import com.lckymn.kevin.test.openejb.domain.User;

@Stateless
public class UserDaoImpl extends AbstractGenericDao<User, Long> implements UserDao
{
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsersByGivenName(String givenName)
	{
		return getEntityManager().createQuery("from User where givenName = ?")
				.setParameter(1, givenName)
				.getResultList();
	}
}

11.3. Services

package com.lckymn.kevin.test.openejb.service;

import java.util.List;

import javax.ejb.Local;

import com.lckymn.kevin.test.openejb.domain.User;

@Local
public interface UserService
{
	User getUser(long id);

	void AddUser(User user);

	List<User> getUserByGivenName(String givenName);
}
package com.lckymn.kevin.test.openejb.service;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import com.lckymn.kevin.test.openejb.dao.UserDao;
import com.lckymn.kevin.test.openejb.domain.User;

@Stateless
public class UserServiceBean implements UserService
{
	@EJB
	private UserDao userDao;

	@Override
	public User getUser(long id)
	{
		return userDao.find(id);
	}

	@Override
	public void AddUser(User user)
	{
		userDao.persist(user);
	}

	@Override
	public List<User> getUserByGivenName(String givenName)
	{
		return userDao.getUsersByGivenName(givenName);
	}

}

11. 4. Servlets

package com.lckymn.kevin.test.openejb.web;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lckymn.kevin.test.openejb.domain.User;
import com.lckymn.kevin.test.openejb.service.UserService;

public class TestServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	@EJB
	private UserService userService;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		User user = new User();
		user.setUsername("kevinlee");
		user.setSurname("Lee");
		user.setGivenName("Kevin");
		user.setEmail("test@test.test");

		userService.AddUser(user);

		HttpSession session = request.getSession();
		session.setAttribute("user", user);

		getServletContext().getRequestDispatcher("/index.jsp")
				.forward(request, response);
	}

}

11.5. Deployment Descriptor (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>test-web-hibernate</display-name>
	<servlet>
		<description></description>
		<display-name>TestServlet</display-name>
		<servlet-name>TestServlet</servlet-name>
		<servlet-class>com.lckymn.kevin.test.openejb.web.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>TestServlet</servlet-name>
		<url-pattern>/Test</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

11. 6. index.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<div>
	<table>
		<tr>
			<td>User ID: </td><td>${user.id }</td>
		</tr>
		<tr>
			<td>Username: </td><td>${user.username }</td>
		</tr>
		<tr>
			<td>Surname: </td><td>${user.surname }</td>
		</tr>
		<tr>
			<td>Given name: </td><td>${user.givenName }</td>
		</tr>
		<tr>
			<td>Email: </td><td>${user.email }</td>
		</tr>
	</table>
</div>
</body>
</html>

12. Run the test application

Access the application URI


http://localhost:8080/test-web-hibernate/Test

It gives me this result.

User ID: 	1
Username: 	kevinlee
Surname: 	Lee
Given name: 	Kevin
Email: 	test@test.test
*** Important ***
Note: Whenever you make changes in your application, Tomcat restarts the application context so that you don’t need to restart the server to apply the changes you made. However, as mentioned several times, you are now using the EJB container so restarting application context is not enough to get your changes applied. Therefore, the EJB container has to be restarted which means you need to restart the Tomcat server to get the changes applied.

© 2014 Kevin's Blog

Theme by Anders NorenUp ↑

%d bloggers like this: