<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Kevin&#039;s Blog &#187; Java Web Application Development</title>
	<atom:link href="http://blog.lckymn.com/category/it/software-development/java-software-development-it/java-web-application-development/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.lckymn.com</link>
	<description>IT, Java, Ubuntu, Linux</description>
	<lastBuildDate>Thu, 12 Jan 2012 05:48:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Catch-Up 01 May, 2010</title>
		<link>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/</link>
		<comments>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 19:04:16 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Web Application Development]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Ubuntu Linux]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[hashCode]]></category>
		<category><![CDATA[Hudson]]></category>
		<category><![CDATA[Issue Tracking System]]></category>
		<category><![CDATA[Java Reflection]]></category>
		<category><![CDATA[javac]]></category>
		<category><![CDATA[JDK7]]></category>
		<category><![CDATA[Kevin]]></category>
		<category><![CDATA[M2Eclipse]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Maven2]]></category>
		<category><![CDATA[Objects]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Sonatype]]></category>
		<category><![CDATA[Spring MVC]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=496</guid>
		<description><![CDATA[<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);"> Some part of <a href="#3. Shadowing Declarations?">3. Bug in Java compiler?Shadowing Declarations?</a> is <a href="#update1-2010-05-10">updated</a> <a href="#update2-2010-05-10">twice</a> on the 10th of May in 2010. </div> <p>I have been very busy and am still busy so haven&#8217;t written anything for quite a while on my blog except for those entries with only one or two sentences. So I&#8217;m quickly writing what I do these days and some <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/">Catch-Up 01 May, 2010</a>...]</p>]]></description>
			<content:encoded><![CDATA[<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
Some part of <a href="#3. Shadowing Declarations?">3. <span style="text-decoration: line-through;"> Bug in Java compiler?</span>Shadowing Declarations?</a> is <a href="#update1-2010-05-10">updated</a> <a href="#update2-2010-05-10">twice</a> on the 10th of May in 2010.
</div>
<p>I have been very busy and am still busy so haven&#8217;t written anything for quite a while on my blog except for those entries with only one or two sentences. So I&#8217;m quickly writing what I do these days and some issues I have dealt with.</p>
<h3><a name="1. Issue with the new m2eclipse (version: 0.10.0.20100209-0800)">1. Issue with the new m2eclipse (version: 0.10.0.20100209-0800)</a></h3>
<p><a href="http://www.sonatype.com/">Sonatype</a> released the new version of <a href="http://m2eclipse.sonatype.org/">m2eclipse</a> in February 2010. Since I updated with it, I had got some problem with maven build through <a href="http://hudson-ci.org/">Hudson</a>.</p>
<p>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&#8217;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&#8217;t really check the details as I didn&#8217;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.<br />
<div id="attachment_501" class="wp-caption alignnone" style="width: 530px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure01.jpg" alt="Build Failure: Project status icon became dark rain clouds" title="00 build failure01" width="520" height="294" class="size-full wp-image-501" /></a><p class="wp-caption-text">Build Failure: Project status icon became dark rain clouds</p></div></p>
<p>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.<br />
<div id="attachment_502" class="wp-caption alignnone" style="width: 336px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure02.jpg" alt="Build Failure: It failed seven times due to the difference between maven2 and maven3" title="00 build failure02" width="326" height="446" class="size-full wp-image-502" /></a><p class="wp-caption-text">Build Failure: It failed seven times due to the difference between maven2 and maven3</p></div><br />
(It happened in February. The build number in the image is 108 but it is now 305).</p>
<p>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 <a href="http://maven.apache.org/guides/mini/guide-encryption.html">password encryption</a> 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&#8217;t really expect that it comes with maven3. Anyway, It&#8217;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.</p>
<h3><a name="2. I have been working on...">2. I have been working on&#8230;</a></h3>
<p>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&#8217;s still an early stage of development.<br />
The issues listed in the following image is a part of the issues I and my colleague have solved and been working on.<br />
<div id="attachment_503" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_00.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_00.jpg" alt="I&#039;m currently working on this project." title="01 Issue Tracking 00" width="640" height="477" class="size-full wp-image-503" /></a><p class="wp-caption-text">I'm currently working on this project.</p></div></p>
<p>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.<br />
<div id="attachment_504" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_01.jpg" alt="Issues of commonly used libraries built by myself" title="01 Issue Tracking 01" width="640" height="335" class="size-full wp-image-504" /></a><p class="wp-caption-text">Issues of commonly used libraries built by myself</p></div></p>
<p>I&#8217;ve also been developing &#8216;Java object to JSON&#8217; 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 <a href="http://json.org/">JSON</a> so why would I make another?  Well, there can be several reasons but major ones are</p>
<ol>
<li>I need it to convert any <a href="http://en.wikipedia.org/wiki/POJO">POJO</a> with only <a href="http://en.wikipedia.org/wiki/Java_annotation">annotations</a> into <a href="http://json.org/">JSON</a>.</li>
<li>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).</li>
<li>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.</li>
<li>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&#8217;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).</li>
</ol>
<p>The following issues are what I have solved for the Java to JSON library.<br />
<div id="attachment_505" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_02.jpg" alt="Issues of my Java object to JSON library" title="01 Issue Tracking 02" width="640" height="451" class="size-full wp-image-505" /></a><p class="wp-caption-text">Issues of my Java object to JSON library</p></div></p>
<p>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 <code>@MVC</code> controllers).  For now, it has only this, yet I will add more features to help Ajax web application development.<br />
<div id="attachment_506" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_03.jpg" alt="Issues of my web method library" title="01 IssueTracking 03" width="640" height="146" class="size-full wp-image-506" /></a><p class="wp-caption-text">Issues of my web method library</p></div></p>
<p>* 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 <a href="http://asm.ow2.org/">ASM</a> or use <a href="http://paranamer.codehaus.org/">ParaNamer</a> (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. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<h3><a name ="3. Shadowing Declarations?">3. <span style="text-decoration: line-through;">Bug in Java compiler?</span> Shadowing Declarations?</a></h3>
<p>I created the Objects utility class based on <a href="http://download.java.net/jdk7/docs/api/java/util/Objects.html">http://download.java.net/jdk7/docs/api/java/util/Objects.html</a>. 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&#8217;s available.  <span style="text-decoration: line-through;">After I made it, I found some weird bug, I believe, in Java compiler.</span> After I used it, I had some problem and though it could be a bug in Java compiler yet <a href="#update2-2010-05-10">it looks like &#8216;shadowing declarations&#8217;.</a></p>
<p>This is the part of Objects class I coded.</p>
<pre class="brush: java; title: ; notranslate">
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() + &quot; cannot be instantiated.&quot;);
    }

    // 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 ...
}
</pre>
<p>The following code is a POJO in which I want to use the Objects.hashCode(Object) method.</p>
<pre class="brush: java; title: ; notranslate">
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())
                &amp;&amp; (this.name == that.getName() ||
                        (null != this.name &amp;&amp; this.name.equals(that.getName())));
    }
}
</pre>
<p>So I changed this code snippet</p>
<pre class="brush: java; gutter: false; highlight: [7]; title: ; notranslate">
@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;
}
</pre>
<p>to this.</p>
<pre class="brush: java; gutter: false; highlight: [3,15]; title: ; notranslate">
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;
    }
}
</pre>
<p>I used static import and hashCode(Object) method in the Objects class. Although, nothing&#8217;s wrong in the code, my Eclipse complains that there is a compile-time error. The following image shows that.<br />
<div id="attachment_511" class="wp-caption alignnone" style="width: 929px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_01.jpg" alt="Objects.hashCode(Object) with static import does not work." title="02 Objects.hashCode 01" width="919" height="837" class="size-full wp-image-511" /></a><p class="wp-caption-text">Objects.hashCode(Object) with static import does not work.</p></div></p>
<p>Yet the same code with no-static import but using class name as the qualifier to use <code>hashCode(Object)</code> method works perfectly. The following code has <code>Objects.hashCode(name)</code> and no compile-time error.</p>
<pre class="brush: java; highlight: [36]; title: ; notranslate">
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())
                &amp;&amp; (this.name == that.getName() || (null != this.name &amp;&amp; this.name.equals(that.getName())));
    }
}
</pre>
<p>The following image shows it has no error in the part where <code>Objects.hashCode(Object)</code> is used..<br />
<div id="attachment_508" class="wp-caption alignnone" style="width: 515px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_02.jpg" alt="Using Class as qualifier to use hashCode works." title="02 Objects.hashCode 02" width="505" height="622" class="size-full wp-image-508" /></a><p class="wp-caption-text">Using Class as qualifier to use hashCode works.</p></div></p>
<p>I wondered if it&#8217;s a bug in the Eclipse or a bug in the Java compiler. So I opened the terminal and tested it.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ 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   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>As it shows, the compiler does totally not understand that the hashCode(Object) method from the Objects class is available and valid.</p>
<p>Is a bug only in the SUN JDK in the Ubuntu Linux repository? So I tried with OpenJDK 6 as well.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ /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   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>The same result&#8230;</p>
<p>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.<br />
<div id="attachment_509" class="wp-caption alignnone" style="width: 622px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/03_update_jdk.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/03_update_jdk.jpg" alt="New version of SUN JDK6 is available in the Ubuntu repository" title="03 Update JDK" width="612" height="640" class="size-full wp-image-509" /></a><p class="wp-caption-text">New version of SUN JDK6 is available in the Ubuntu repository</p></div></p>
<p>It still has the same problem.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ 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   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>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.</p>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
<a name="update1-2010-05-10">* Update1 (2010-05-10)</a><br />
I also tested it with the Java compiler in the JDK 6 (1.6.0_16) for Windows and got the same result. <span style="text-decoration: line-through">It seem like static import cannot handle method overloading. I didn&#8217;t have time to research to find the details but based on my testing, method overloading cannot be used with static import.<br />
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.</span><br />
Take a look at the following code.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    public static void test(Object... object)
    {
        System.out.println(&quot;SomeHelper.test()&quot;);
    }
}
</pre>
<pre class="brush: java; highlight: [3,14,17]; title: ; notranslate">
package com.lckymn.kevin.test;

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

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

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

        Object object = new Object();
        test(object);    // compile-time error
    }
}
</pre>
<p><span style="text-decoration: line-through">Since a method with varargs can take no argument when it&#8217;s called, Test.test() and SomeHelper.test(Object&#8230; 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.</span><br />
So the following code has no compile-time error and displays <code>Test.test()</code>.</p>
<pre class="brush: java; highlight: [3]; title: ; notranslate">
package com.lckymn.kevin.test;

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

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

    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);
    }
}
</pre>
<p>It displays <code>Test.test()</code>.</p>
<p>What if the helper class has test() method with no arguments and the Test class has test() method with varargs then call <code>test()</code>? The same result! It still calls Test&#8217;s test() method with varargs (<code>Test.test(Object... object)</code>).</p>
<pre class="brush: java; highlight: [10]; title: ; notranslate">
package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    public static void test()
    {
        System.out.println(&quot;SomeHelper.test()&quot;);
    }
}
</pre>
<pre class="brush: java; highlight: [3,7]; title: ; notranslate">
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(&quot;Test.test(Object...object)&quot;);
    }

    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);
    }
}
</pre>
<p>It displays <code>Test.test(Object...object)</code>
</div>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
<a name="update2-2010-05-10">Update2 (2010-05-10)</a><br />
It is more likely to be <a href="http://java.sun.com/docs/books/jls/third_edition/html/names.html#34133">&#8216;Shadowing Declarations&#8217;</a>. Although, I couldn&#8217;t find the exactly matching case from the <a href="http://java.sun.com/docs/books/jls/">JLS</a> yet, it makes more sense if the method imported by static-import is shadowed.
</div>
<h3><a name="4. Using Objects">4. Using Objects</a></h3>
<p>By the way, the Objects class is simple but very useful.<br />
with it, the highlighted parts of the following code can</p>
<pre class="brush: java; highlight: [53,54,55,56,57,72,73,74,75]; title: ; notranslate">
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 &amp;&amp; this.bankName.equals(that.getBankName())))
                &amp;&amp; (this.bsbNumber == that.getBsbNumber() ||
                   (null != this.bsbNumber &amp;&amp; this.bsbNumber.equals(that.getBsbNumber())));
    }
}
</pre>
<p>become like this</p>
<pre class="brush: java; highlight: [55,70,71]; title: ; notranslate">
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())
               &amp;&amp; Objects.equals(this.bsbNumber, that.getBsbNumber());
    }
}
</pre>
<p>So these five lines in the hashCode method</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
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;
</pre>
<p>become</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return Objects.hash(bankName, bankName);
</pre>
<p>and these four lines in the equals method</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return (this.bankName == that.getBankName() ||
       (null != this.bankName &amp;&amp; this.bankName.equals(that.getBankName())))
        &amp;&amp; (this.bsbNumber == that.getBsbNumber() ||
           (null != this.bsbNumber &amp;&amp; this.bsbNumber.equals(that.getBsbNumber())));
</pre>
<p>become</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return Objects.equals(this.bankName, that.getBankName())
       &amp;&amp; Objects.equals(this.bsbNumber, that.getBsbNumber());
</pre>
<p>Although one might say that I can use <a href="http://projectlombok.org/">Lombok</a> 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. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
That&#8217;s it.<br />
I perhaps have more to say yet am getting tired (4:55 AM :O). So I&#8217;m calling it a night. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Web Service Development using Tomcat and OpenEJB</title>
		<link>http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/</link>
		<comments>http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 05:42:30 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Web Application Development]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[@WebService]]></category>
		<category><![CDATA[Apache Tomcat]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Eclipse Ganymede]]></category>
		<category><![CDATA[Eclipse JEE]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[EJB3]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Java EE 5]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[OpenEJB]]></category>
		<category><![CDATA[OpenJPA]]></category>
		<category><![CDATA[Tomcat]]></category>
		<category><![CDATA[Web Service]]></category>
		<category><![CDATA[Web Service Client]]></category>
		<category><![CDATA[Web Service Development]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=432</guid>
		<description><![CDATA[<p>In addition to the previous post, <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">Java EE Application Development using Tomcat, OpenEJB and Hibernate</a>, 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 <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">the previous post</a>, so if you haven&#8217;t read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> yet, better read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> first.</p> <p>Firstly, create a web service interface then put the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation.</p> package com.lckymn.kevin.test.openejb.webservice; import javax.jws.WebService; import <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/">Web Service Development using Tomcat and OpenEJB</a>...]</p>]]></description>
			<content:encoded><![CDATA[<p>In addition to the previous post, <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">Java EE Application Development using Tomcat, OpenEJB and Hibernate</a>, 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 <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">the previous post</a>, so if you haven&#8217;t read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> yet, better read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> first.</p>
<p>Firstly, create a web service interface then put the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation.</p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
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);
}
</pre>
<p>Secondly, create a class implmenting the web service interface with also the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation then specify the <code>targetNamespace</code> and the <code>serviceName</code> as you wish. In my case, these are<br />
<code><br />
targetNamespace: "http://webservice.webhibernate.test"<br />
serviceName: "testWebService"<br />
</code><br />
To use the UserService EJB, injected by OpenEJB, make the web service class session EJB with the @Stateless annotation.</p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
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 = &quot;http://webservice.webhibernate.test&quot;, serviceName = &quot;testWebService&quot;)
public class TestWebServiceImpl implements TestWebService
{
	@EJB
	private UserService userService;

	@Override
	public User getUser(Long id)
	{
		return userService.getUser(id);
	}
}
</pre>
<p>The class above simply returns a User entity object acquired from the <code>UserService</code> EJB, made in the previous post.</p>
<p>That&#8217;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.</p>
<p>Now, let&#8217;s make a web service client. To make a very simple example client, I&#8217;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.</p>
<p>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 <code>HttpSession</code> to the JSP page to display.</p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
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(&quot;http://localhost:8080/TestWebServiceImpl?wsdl&quot;), new QName(
				&quot;http://webservice.webhibernate.test&quot;, &quot;testWebService&quot;));
		TestWebService testWebService = service.getPort(TestWebService.class);

		String userIdParam = request.getParameter(&quot;userId&quot;);

		HttpSession session = request.getSession();
		if (null == userIdParam || 0 == userIdParam.length())
		{
			session.removeAttribute(&quot;userFound&quot;);
		}
		else
		{
			Long userId = Long.parseLong(userIdParam);
			User user = testWebService.getUser(userId);
			session.setAttribute(&quot;userFound&quot;, user);
		}
		getServletContext().getRequestDispatcher(&quot;/WEB-INF/jsp/webServiceClient.jsp&quot;)
				.forward(request, response);
	}
}
</pre>
<p>This is just a simple example thus I omitted validation (e.g. checking whether the userId is &#8216;long&#8217; type or not) and exception handling. </p>
<p>The WSDL location is the server URI + &#8220;/&#8221; + web service class name + &#8220;?wsdl&#8221;.<br />
<code>http://localhost:8080/TestWebServiceImpl?wsdl</code><br />
The parameters of the <a href="http://java.sun.com/javase/6/docs/api/javax/xml/namespace/QName.html" target="_blank">QName</a> constructor are <code>namespaceURI</code> and <code>localPart</code>, and these are defined in the web service. If you look at the web service code again, these can easily be found from the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation.</p>
<pre class="brush: java; gutter: false; highlight: [1]; title: ; notranslate">
@WebService(targetNamespace = &quot;http://webservice.webhibernate.test&quot;, serviceName = &quot;testWebService&quot;)
public class TestWebServiceImpl implements TestWebService
{
	...
}
</pre>
<p>The value of the <code>targetNamespace</code> element is the <code>namespaceURI</code> of the <code>QName</code> constructor, and the value of the <code>serviceNmae</code> element is the <code>localPart</code>.</p>
<p>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.</p>
<pre class="brush: xml; highlight: [14,15,16,17,18,19,20,21,22,23]; tab-size: 4; title: ; toolbar: true; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot; id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
  &lt;display-name&gt;test-web-hibernate&lt;/display-name&gt;
  &lt;servlet&gt;
    &lt;description&gt;&lt;/description&gt;
    &lt;display-name&gt;TestServlet&lt;/display-name&gt;
    &lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.lckymn.kevin.test.openejb.web.TestServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/Test&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  &lt;servlet&gt;
    &lt;description&gt;&lt;/description&gt;
    &lt;display-name&gt;TestWebServiceClientServlet&lt;/display-name&gt;
    &lt;servlet-name&gt;TestWebServiceClientServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.lckymn.kevin.test.openejb.web.TestWebServiceClientServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;TestWebServiceClientServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/TestWebServiceClient&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>
<p>Finally, add a JSP file to enter the userId to search a user and to display the user info.<br />
In my case, I added the file to the <code>application/WebContent/WEB-INF/jsp</code> directory which is the same location that I set in the <code>TestWebServiceClientServlet</code> (look at the TestWebServiceClientServlet code above).<br />
<code>test-web-hibernate/WebContent/WEB-INF/jsp/webServiceClient.jsp</code></p>
<pre class="brush: xml; tab-size: 4; title: ; toolbar: true; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
&lt;form name=&quot;userForm&quot; action=&quot;TestWebServiceClient&quot; method=&quot;post&quot; &gt;
	&lt;input type=&quot;text&quot; name=&quot;userId&quot; value=&quot;&quot; /&gt; &lt;input type=&quot;submit&quot; name=&quot;userIdSubmit&quot; value=&quot;Search&quot; /&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;table&gt;
		&lt;tr&gt;
			&lt;td&gt;User ID: &lt;/td&gt;&lt;td&gt;${userFound.id }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Username: &lt;/td&gt;&lt;td&gt;${userFound.username }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Surname: &lt;/td&gt;&lt;td&gt;${userFound.surname }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Given name: &lt;/td&gt;&lt;td&gt;${userFound.givenName }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Email: &lt;/td&gt;&lt;td&gt;${userFound.email }&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>To test it, open the browser and enter the following URI.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">

http://localhost:8080/test-web-hibernate/TestWebServiceClient
</pre>
<p>It displays the screen like below<br />
<div id="attachment_436" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg" alt="Enter userId and click the &#039;Search&#039; button" title="Web Service Client Test 01" width="702" height="268" class="size-full wp-image-436" /></a><p class="wp-caption-text">Enter userId and click the 'Search' button</p></div><br />
-Enter a userId to search then click the &#8216;Search&#8217; button.</p>
<p>It displays the result yet there is one problem. It doesn&#8217;t display the userId.<br />
<div id="attachment_437" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test02.jpg" alt="The Search Result: userId is not displayed" title="Web Service Client Test 02" width="702" height="268" class="size-full wp-image-437" /></a><p class="wp-caption-text">The Search Result: userId is not displayed</p></div><br />
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.</p>
<p>There are two simple ways to solve this problem. Either way works so choose whichever you like.</p>
<p>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.</p>
<pre class="brush: java; highlight: [19,20,21,22]; tab-size: 4; title: ; toolbar: true; notranslate">
@Entity
@Table(name = &quot;users&quot;)
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

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

	...

	public Long getId()
	{
		return id;
	}

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

	...
}
</pre>
<p>OR</p>
<p>2. If you add the <a href="http://java.sun.com/javase/6/docs/api/javax/xml/bind/annotation/XmlElement.html" target="_blank">@XmlElement</a> annotation to the id field and set the value of the <code>required</code> element to <code>true</code>, the id field is included even without the setter method.</p>
<pre class="brush: java; highlight: [15]; tab-size: 4; title: ; toolbar: true; notranslate">
...

import javax.xml.bind.annotation.XmlElement;

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

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

	...

	public Long getId()
	{
		return id;
	}

	// No setId() required

	...
}
</pre>
<p>Now, test if it works.<br />
<div id="attachment_436" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg" alt="Enter userId and click the &#039;Search&#039; button" title="Web Service Client Test 01" width="702" height="268" class="size-full wp-image-436" /></a><p class="wp-caption-text">Enter userId and click the 'Search' button</p></div></p>
<p>It works!<br />
<div id="attachment_438" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test03.jpg" alt="The Search Result: userId is displayed correctly" title="Web Service Client Test 03" width="702" height="268" class="size-full wp-image-438" /></a><p class="wp-caption-text">The Search Result: userId is displayed correctly</p></div></p>
<p>There are also other ways and tools to create a web service in Java. I used to use <a href="http://ws.apache.org/axis/" target="_blank">Apache Axis</a> then later moved to <a href="http://xfire.codehaus.org/" target="_blank">XFire</a>. Now, I use <a href="http://cxf.apache.org/" target="_blank">Apache CXF</a> 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 <a href="http://ws.apache.org/axis/java/user-guide.html#WSDL2JavaBuildingStubsSkeletonsAndDataTypesFromWSDL" target="_blank">WSDL2Java</a> from <a href="http://ws.apache.org/axis/" target="_blank">Apache Axis</a> or <a href="http://ws.apache.org/axis2/1_3/userguide-creatingclients.html" target="_blank">WSDL2Java</a> from <a href="http://ws.apache.org/axis2/" target="_blank">Apache Axis2</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Java EE Application Development using Tomcat, OpenEJB and Hibernate</title>
		<link>http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/</link>
		<comments>http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 17:06:59 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Web Application Development]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Apache Tomcat]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Eclipse Ganymede]]></category>
		<category><![CDATA[Eclipse JEE]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[EJB3]]></category>
		<category><![CDATA[Generic DAO]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Java EE 5]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[OpenEJB]]></category>
		<category><![CDATA[OpenJPA]]></category>
		<category><![CDATA[Software Development Environment]]></category>
		<category><![CDATA[Tomcat]]></category>
		<category><![CDATA[Web Application Development]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=380</guid>
		<description><![CDATA[<p>Java EE Application Development using Tomcat, OpenEJB and Hibernate</p> <p>Before I start writing this blog entry, I&#8217;d better point out a few things.</p> This blog entry is not about how to make a good <a href="http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition" target="_blank">Java EE</a> application yet is about how to use <a href="http://openejb.apache.org/" target="_blank">OpenEJB</a> on <a href="http://tomcat.apache.org/" target="_blank">Apache Tomcat server</a> with <a href="https://www.hibernate.org/" target="_blank">Hibernate</a> as an implementation of the <a href="http://en.wikipedia.org/wiki/Java_Persistence_API" target="_blank">JPA</a>. If you are looking for better Java EE development or similar, this one is <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/">Java EE Application Development using Tomcat, OpenEJB and Hibernate</a>...]</p>]]></description>
			<content:encoded><![CDATA[<p>Java EE Application Development using Tomcat, OpenEJB and Hibernate</p>
<p>Before I start writing this blog entry, I&#8217;d better point out a few things.</p>
<ul>
<li>This blog entry is not about how to make a good <a href="http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition" target="_blank">Java EE</a> application yet is about how to use <a href="http://openejb.apache.org/" target="_blank">OpenEJB</a> on <a href="http://tomcat.apache.org/" target="_blank">Apache Tomcat server</a> with <a href="https://www.hibernate.org/" target="_blank">Hibernate</a> as an implementation of the <a href="http://en.wikipedia.org/wiki/Java_Persistence_API" target="_blank">JPA</a>.  If you are looking for better Java EE development or similar, this one is not for you. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li> I don&#8217;t have enough time to explain all the details of how to install JDK, Eclipse, Tomcat and so on. So this post doesn&#8217;t have that level of details. I simply assume that you&#8217;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.</li>
<li>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.</li>
</ul>
<h2>1. Development Environment</h2>
<p>First of all, I&#8217;m going to list the development environment and tools I have for this introductory tutorial post.<br />
(Click each name and it will take you to the download page).</p>
<p>OS: <a href="http://www.ubuntu.com" target="_blank">Ubuntu Linux</a> <a href="http://releases.ubuntu.com/9.04/" target="_blank">Jaunty Jackalope 9.04 Desktop 64bit</a><br />
Java: <a href="http://java.sun.com/javase/downloads" target="_blank">Sun JDK 1.6.0_16 (64 bit)</a> (it&#8217;s from the Ubuntu repository).<br />
Database: <a href="http://dev.mysql.com/downloads/mysql/5.0.html" target="_blank">MySQL Community Server 5.0</a> (it&#8217;s from the Ubuntu repository).<br />
JDBC Driver: <a href="http://dev.mysql.com/downloads/connector/j/5.1.html" target="_blank">MySQL Connector/J 5.1.10</a><br />
Eclipse: <a href="http://eclipse.org/downloads/packages/release/ganymede/sr2" target="_blank">Eclipse IDE for Java EE Developer Ganymede SR2 (Eclipse 3.4.2)</a><br />
Tomcat: <a href="http://tomcat.apache.org/download-60.cgi" target="_blank">Tomcat 6.0.20</a><br />
OpenEJB: <a href="http://openejb.apache.org/download.html" target="_blank">OpenEJB 3.1.1 (openejb.war)</a><br />
Hibernate: <a href="http://sourceforge.net/projects/hibernate/files/" target="_blank">Hibernate 3.2.1GA</a> (including hibernate-3.2.1.ga, hibernate-annotations-3.2.1.ga, hibernate-entitymanager-3.2.1.ga)</p>
<h2>2. Installing OpenEJB</h2>
<p>Java EE server normally means a Java application server which consists of a <a href="http://en.wikipedia.org/wiki/Java_Servlet" target="_blank">Servlet</a> container and an <a href="http://en.wikipedia.org/wiki/EJB_container" target="_blank">EJB</a> 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&#8217;re using the frameworks supporting EJB such as Spring framework. &#8220;So if I use Tomcat server and Spring framework, do I not need OpenEJB or other Java EE servers to use EJB?&#8221; No, you don&#8217;t.</p>
<p>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.</p>
<p>Before installing OpenEJB, don&#8217;t forget to copy JDBC driver that is, in this post, MySQL Connector/J to the $TOMCAT/lib directory.<br />
-Copy the Connector/J jar file to the Tomcat&#8217;s library directory ($TOMCAT_HOME/lib)<br />
<div id="attachment_381" class="wp-caption alignnone" style="width: 727px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j01.jpg" alt="Select Connector/J and Extract to the $TOMCAT/lib directory." title="Extract Connector/J" width="717" height="493" class="size-full wp-image-381" /></a><p class="wp-caption-text">Select Connector/J and Extract to the $TOMCAT/lib directory.</p></div></p>
<div id="attachment_382" class="wp-caption alignnone" style="width: 432px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j02.jpg" alt="Make sure the Connector/J jar file is in the $TOMCAT/lib directory." title="Check Connector/J is in the $TOMCAT/lib directory" width="422" height="395" class="size-full wp-image-382" /></a><p class="wp-caption-text">Make sure the Connector/J jar file is in the $TOMCAT/lib directory.</p></div>
<p>-Run Eclipse and add Tomcat server: Menu &#8211; Window -> Preferences -> Server -> Runtime Environments -> Add</p>
<p>-Download the openejb.war, OpenEJB for Tomcat, and import the file from Eclipse.<br />
-Right click on the project explorer -> Import -> WAR file<br />
<div id="attachment_383" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb01.jpg" alt="Right Click on the project explorer -&gt; Import -&gt; WAR File" title="Import OpenEJB 01" width="688" height="509" class="size-full wp-image-383" /></a><p class="wp-caption-text">Right Click on the project explorer -> Import -> WAR File</p></div></p>
<p>-Click the &#8216;Browse&#8217; button and select the openejb.war file -> Select your Tomcat 6.0 as the target runtime. -> Click the &#8216;Finish&#8217; button.<br />
<div id="attachment_384" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb02.jpg" alt="Click the &#039;Browse&#039; button and select the openejb.war file -&gt; Select your Tomcat 6.0 as the target runtime. -&gt; Click the &#039;Finish&#039; button." title="Import OpenEJB 02" width="613" height="408" class="size-full wp-image-384" /></a><p class="wp-caption-text">Click the 'Browse' button and select the openejb.war file -> Select your Tomcat 6.0 as the target runtime. -> Click the 'Finish' button.</p></div></p>
<h2>3. Add OpenEJB project to the Server to deploy</h2>
<p>-Right click on the server name in the &#8216;Server&#8217; view -> Select the &#8216;Add and Remove Projects&#8230;&#8217;<br />
<div id="attachment_385" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server01.jpg" alt="Right click on the server name in the &#039;Server&#039; view -&gt; Select the &#039;Add and Remove Projects...&#039;" title="03 Add to the Server 01" width="688" height="509" class="size-full wp-image-385" /></a><p class="wp-caption-text">Right click on the server name in the 'Server' view -> Select the 'Add and Remove Projects...'</p></div></p>
<p>-Select openejb -> Click the &#8216;Add&#8217; button -> Click the &#8216;Finish&#8217; button<br />
<div id="attachment_386" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server02.jpg" alt="Select openejb -&gt; Click the &#039;Add&#039; button -&gt; Click the &#039;Finish&#039; button" title="03 Add_to the Server 02" width="613" height="546" class="size-full wp-image-386" /></a><p class="wp-caption-text">Select openejb -> Click the 'Add' button -> Click the 'Finish' button</p></div></p>
<p>-openejb is ready to be deployed.<br />
<div id="attachment_387" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server03.jpg" alt="openejb is deployed." title="07 Add to the Server 03" width="688" height="509" class="size-full wp-image-387" /></a><p class="wp-caption-text">openejb is deployed.</p></div></p>
<p>-Now run the server to deploy openejb.<br />
<div id="attachment_388" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server01.jpg" alt="Run the server to deploy openejb" title="08 Run the Server 01" width="688" height="509" class="size-full wp-image-388" /></a><p class="wp-caption-text">Run the server to deploy openejb</p></div></p>
<p>-openejb is successfully deployed.<br />
<div id="attachment_389" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server02.jpg" alt="the openejb is successfully deployed." title="09 Run the Server 02" width="688" height="509" class="size-full wp-image-389" /></a><p class="wp-caption-text">the openejb is successfully deployed.</p></div></p>
<h2>4. Set up DataSource</h2>
<p>-openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace.<br />
<div id="attachment_390" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file01.jpg" alt="openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace." title="10 Copy openejb.xml file 01" width="688" height="509" class="size-full wp-image-390" /></a><p class="wp-caption-text">openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace.</p></div></p>
<p>If you are using Tomcat without OpenEJB and want to create a DataSource, you might do by putting the DataSource info to Tomcat&#8217;s server.xml file or your application&#8217;s context configuration file (your_app/META-INF/context.xml).  Yet to create the DataSource for JPA, you need to do through <code>openejb.xml</code> file. It is created in the Tomcat folder in the <code>.metadata</code> 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 &#8216;/home/username/workspace&#8217;, the Tomcat is in &#8216;/home/username/test-workspace/.metadata/.plugins/org.eclipse.wst.server.core&#8217; and the openejb.xml file can be found in the &#8216;/home/username/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf&#8217; directory.</p>
<p>-Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace.<br />
<div id="attachment_391" class="wp-caption alignnone" style="width: 625px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file02.jpg" alt="Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace." title="11 Copy openejb.xml file 02" width="615" height="309" class="size-full wp-image-391" /></a><p class="wp-caption-text">Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace.</p></div><br />
<div id="attachment_392" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file03.jpg" alt="Paste the file to the Tomcat configuration folder of the Eclipse workspace." title="12 Copy openejb.xml file 03" width="688" height="509" class="size-full wp-image-392" /></a><p class="wp-caption-text">Paste the file to the Tomcat configuration folder of the Eclipse workspace.</p></div></p>
<p>-Open the &#8216;openejb.xml&#8217; file then you can find the default DataSources.<br />
<div id="attachment_395" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource01.jpg" alt="Open the &#039;openejb.xml&#039; file then you can find the default DataSources" title="13 Set up the datasource 01" width="688" height="509" class="size-full wp-image-395" /></a><p class="wp-caption-text">Open the 'openejb.xml' file then you can find the default DataSources</p></div><br />
One is JTA managed while the other is not. Both use <a href="http://hsqldb.org" title="HSQLDB" target="_blank">HSQLDB</a> which is a Java database. If you don&#8217;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.</p>
<p>-Add the following lines and modify for your own database.</p>
<pre class="brush: xml; gutter: false; title: ; notranslate">
&lt;Resource id=&quot;mysqlDataSource&quot; type=&quot;javax.sql.DataSource&quot;&gt;
	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
&lt;/Resource&gt;
</pre>
<div id="attachment_396" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource02.jpg" alt="DataSource to access the MySQL database." title="14 Set up the datasource 02" width="688" height="624" class="size-full wp-image-396" /></a><p class="wp-caption-text">DataSource to access the MySQL database.</p></div>
<p>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.</p>
<h2>5. Install Hibernate</h2>
<p>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&#8217;s lib directory. Thus just like you need to copy the JDBC driver, in this post it&#8217;s &#8216;Connector/J&#8217;, to the tomcat&#8217;s lib directory, the hibernate jar files should be placed in the Tomcat&#8217;s lib directory.</p>
<p>Otherwise, you will get an error like this.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
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
</pre>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
So you have to copy the hibernate to the Tomcat&#8217;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.</p>
<p><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/hibernate-jpa-3.2.1ga.tar.gz">Click Here to Download the File!</a></p>
<p>After downloading, extract all the files inside to the Tomcat&#8217;s lib directory (<code>$TOMCAT/lib</code>) just like what you did to install JDBC driver, Connector/J.
</div>
<h2>6. Adding logger configuration (Optional)</h2>
<p>By default, OpenEJB creates a log file in the Eclipse&#8217;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.</p>
<p>-Right click on the Tomcat configuration folder -> Select &#8216;New&#8217; -> Select &#8216;File&#8217; -> crated a file with the name &#8216;logging.properties&#8217;.<br />
<div id="attachment_398" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config01.jpg" alt="Right click on the Tomcat configuration folder -&gt; Select &#039;New&#039; -&gt; Select &#039;File&#039; -&gt; crated a file with the name &#039;logging.properties&#039;." title="15 Add the logger config 01" width="688" height="543" class="size-full wp-image-398" /></a><p class="wp-caption-text">Right click on the Tomcat configuration folder -> Select 'New' -> Select 'File' -> crated a file with the name 'logging.properties'.</p></div></p>
<p>-Open the file and put the following lines</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
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
</pre>
<div id="attachment_399" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config02.jpg" alt="Put the logger config details" title="16 Add the logger config 02" width="688" height="543" class="size-full wp-image-399" /></a><p class="wp-caption-text">Put the logger config details</p></div>
<h2>7. Create Web Application Project</h2>
<p>Now, you can develop a web application using EJB3 and Hibernate as the implementation of the JPA.</p>
<p>-Right click on the project explorer -> Select &#8216;New&#8217; -> Select &#8216;Dynamic Web Project&#8217;<br />
<div id="attachment_400" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project01.jpg" alt="Right click on the project explorer -&gt; Select &#039;New&#039; -&gt; Select &#039;Dynamic Web Project&#039;" title="17 Create Project 01" width="688" height="543" class="size-full wp-image-400" /></a><p class="wp-caption-text">Right click on the project explorer -> Select 'New' -> Select 'Dynamic Web Project'</p></div></p>
<p>-Put the name you like -> Select the &#8216;Apache Tomcat v6.0&#8242; as the target runtime -> Select &#8217;2.5&#8242; as the version of &#8216;Dynamic Web Module&#8217; -> Select the default Tomcat configuration or your own one -> Click the &#8216;Next&#8217; button.<br />
<div id="attachment_401" class="wp-caption alignnone" style="width: 715px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project02.jpg" alt="Put the name you like -&gt; Select the &#039;Apache Tomcat v6.0&#039; as the target runtime -&gt; Select &#039;2.5&#039; as the version of &#039;Dynamic Web Module&#039; -&gt; Select the default Tomcat configuration or your own one -&gt; Click the &#039;Next&#039; button." title="18 Create Project 02" width="705" height="640" class="size-full wp-image-401" /></a><p class="wp-caption-text">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.</p></div></p>
<p>-Change the project context root and directory names if you like -> Click the &#8216;Finish&#8217; button.<br />
<div id="attachment_402" class="wp-caption alignnone" style="width: 715px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project03.jpg" alt="Change the project context root and directory names if you like -&gt; Click the &#039;Finish&#039; button." title="19 Create Project 03" width="705" height="640" class="size-full wp-image-402" /></a><p class="wp-caption-text">Change the project context root and directory names if you like -> Click the 'Finish' button.</p></div></p>
<p>-Right click on the Server to add the project -> Select the &#8216;Add and Remove Projects&#8230;&#8217;.<br />
<div id="attachment_403" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project04.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project04.jpg" alt="Right click on the Server to add the project -&gt; Select the &#039;Add and Remove Projects...&#039;." title="20 Create Project 04" width="688" height="543" class="size-full wp-image-403" /></a><p class="wp-caption-text">Right click on the Server to add the project -> Select the 'Add and Remove Projects...'.</p></div></p>
<p>-Select the project you created -> Click the &#8216;Add&#8217; button -> Click the &#8216;Finish&#8217; button.<br />
<div id="attachment_404" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project05.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project05.jpg" alt="Select the project you created -&gt; Click the &#039;Add&#039; button -&gt; Click the &#039;Finish&#039; button." title="21 Create Project 05" width="613" height="546" class="size-full wp-image-404" /></a><p class="wp-caption-text">Select the project you created -> Click the 'Add' button -> Click the 'Finish' button.</p></div></p>
<p>-Both openejb and your project are added.<br />
<div id="attachment_405" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project06.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project06.jpg" alt="Both openejb and your project are added." title="22 Create Project 06" width="688" height="543" class="size-full wp-image-405" /></a><p class="wp-caption-text">Both openejb and your project are added.</p></div></p>
<h2>8. Make JPA Project</h2>
<p>To use the JPA support feature of Eclipse, you need to change the project facet configuration.</p>
<p>-Right click on your project -> Select the &#8216;Properties&#8217;.<br />
<div id="attachment_406" class="wp-caption alignnone" style="width: 702px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project01.jpg" alt="Right click on your project -&gt; Select the &#039;Properties&#039;." title="23 Make JPA Project 01" width="692" height="525" class="size-full wp-image-406" /></a><p class="wp-caption-text">Right click on your project -> Select the 'Properties'.</p></div></p>
<p>-Select the &#8216;Project Facets&#8217; -> Check &#8216;Java Persistence 1.0&#8242; -> Click the &#8216;Further configuration available&#8230;&#8217; link.<br />
<div id="attachment_407" class="wp-caption alignnone" style="width: 666px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project02.jpg" alt="Select the &#039;Project Facets&#039; -&gt; Check &#039;Java Persistence 1.0&#039; -&gt; Click the &#039;Further configuration available...&#039; link." title="24 Make JPA Project 02" width="656" height="574" class="size-full wp-image-407" /></a><p class="wp-caption-text">Select the 'Project Facets' -> Check 'Java Persistence 1.0' -> Click the 'Further configuration available...' link.</p></div></p>
<p>-Select &#8216;Generic&#8217; -> Select &#8216;None&#8217; or your own connection or add a new connection if you wish -> Select &#8216;Use implementation provided by server runtime&#8217; -> Select &#8216;Discover annotated classes automatically&#8217; -> Uncheck &#8216;Create orm.xml&#8217; option -> Click the &#8216;OK&#8217; button.<br />
<div id="attachment_408" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project03.jpg" alt="Select &#039;Generic&#039; -&gt; Select &#039;None&#039; or your own connection or add a new connection if you wish -&gt; Select &#039;Use implementation provided by server runtime&#039; -&gt; Select &#039;Discover annotated classes automatically&#039; -&gt; Uncheck &#039;Create orm.xml&#039; option -&gt; Click the &#039;OK&#039; button." title="25 Make JPA Project 03" width="613" height="660" class="size-full wp-image-408" /></a><p class="wp-caption-text">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.</p></div><br />
(I do usually not set up the connection yet if you want to generate entity classes from the existing tables, you&#8217;d better set it up).</p>
<h2>9. Add Java EE 5 API library file</h2>
<p>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.</p>
<p>-Select &#8216;Java Build Path on the left-hand side menu -> Select the &#8216;Libraries&#8217; tab -> Click the &#8216;Add JARs&#8230;&#8217; button.<br />
<div id="attachment_409" class="wp-caption alignnone" style="width: 914px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api02.jpg" alt="Select &#039;Java Build Path on the left-hand side menu -&gt; Select the &#039;Libraries&#039; tab -&gt; Click the &#039;Add JARs...&#039; button." title="26 Add JavaEE API 02" width="904" height="584" class="size-full wp-image-409" /></a><p class="wp-caption-text">Select 'Java Build Path on the left-hand side menu -> Select the 'Libraries' tab -> Click the 'Add JARs...' button.</p></div></p>
<p>-Select &#8216;javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -> Click the &#8216;OK&#8217; button.<br />
<div id="attachment_410" class="wp-caption alignnone" style="width: 480px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api03.jpg" alt="Select &#039;javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -&gt; Click the &#039;OK&#039; button." title="27 Add JavaEE 5 API 03" width="470" height="761" class="size-full wp-image-410" /></a><p class="wp-caption-text">Select 'javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -> Click the 'OK' button.</p></div></p>
<p>-Click the &#8216;OK&#8217; button.<br />
<div id="attachment_411" class="wp-caption alignnone" style="width: 914px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api04.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api04.jpg" alt="Click the &#039;OK&#039; button." title="28 Add JavaEE 5 API 04" width="904" height="584" class="size-full wp-image-411" /></a><p class="wp-caption-text">Click the 'OK' button.</p></div><br />
-JPA configuration file (persistence.xml) is added.<br />
<div id="attachment_412" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml01.jpg" alt="JPA configuration file (persistence.xml) is added" title="29 Config persistence_xml 01" width="688" height="525" class="size-full wp-image-412" /></a><p class="wp-caption-text">JPA configuration file (persistence.xml) is added</p></div></p>
<h2>10. Configure persistence.xml file</h2>
<p>It&#8217;s the last step before starting to programme the actual application.</p>
<p>-Open the persistence.xml file -> Type &#8216;org.hibernate.ejb.HibernatePersistence&#8217; to the &#8216;Persistence Provider&#8217;.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
org.hibernate.ejb.HibernatePersistence
</pre>
<div id="attachment_413" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml02.jpg" alt="Open the persistence.xml file -&gt; put &#039;org.hibernate.ejb.HibernatePersistence&#039; to the &#039;Persistence Provider&#039;." title="30 Config persistence_xml 02" width="688" height="543" class="size-full wp-image-413" /></a><p class="wp-caption-text">Open the persistence.xml file -> put 'org.hibernate.ejb.HibernatePersistence' to the 'Persistence Provider'.</p></div>
<p>-Click the &#8216;Connection&#8217; tab -> Select the &#8216;JTA&#8217; as the &#8216;Transaction Type&#8217; -> Type &#8216;mysqlDataSource&#8217; or your datasource name added in the previous steps. -> Press &#8216;Ctrl + S&#8217; keys to save the file.<br />
<div id="attachment_414" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml03.jpg" alt="Click the &#039;Connection&#039; tab -&gt; Select the &#039;JTA&#039; as the &#039;Transaction Type&#039; -&gt; Type &#039;mysqlDataSource&#039; or your datasource name added in the previous steps. -&gt; Press &#039;Ctrl + S&#039; keys to save the file." title="31 Config persistence.xml 03" width="688" height="543" class="size-full wp-image-414" /></a><p class="wp-caption-text">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.</p></div></p>
<p>-If you select the &#8216;Source&#8217; tab, you should see the XML like this.<br />
<div id="attachment_415" class="wp-caption alignnone" style="width: 740px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml04.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml04.jpg" alt="If you select the &#039;Source&#039; tab, you should see the XML like above." title="32 Config persistence.xml 04" width="730" height="537" class="size-full wp-image-415" /></a><p class="wp-caption-text">If you select the 'Source' tab, you should see the XML like above.</p></div></p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;persistence version=&quot;1.0&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;&gt;
	&lt;persistence-unit name=&quot;test-web-hibernate&quot; transaction-type=&quot;JTA&quot;&gt;
		&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
		&lt;jta-data-source&gt;mysqlDataSource&lt;/jta-data-source&gt;
	&lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
<p>-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.</p>
<pre class="brush: xml; highlight: [9,10,11]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;persistence version=&quot;1.0&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;&gt;
	&lt;persistence-unit name=&quot;test-web-hibernate&quot; transaction-type=&quot;JTA&quot;&gt;
		&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
		&lt;jta-data-source&gt;mysqlDataSource&lt;/jta-data-source&gt;
		&lt;properties&gt;
			&lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;create&quot; /&gt;
		&lt;/properties&gt;
	&lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
<h2>11. Test</h2>
<p>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.</p>
<h3>11.1. Entity classes</h3>
<p>Here is my only entity class in this test.</p>
<pre class="brush: java; title: ; notranslate">
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 = &quot;users&quot;)
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

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

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

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

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

	@Column(name = &quot;email&quot;, 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 &amp;&amp; username.equals(that.getUsername())));
	}

	@Override
	public int hashCode()
	{
		return (null == username ? 0 : username.hashCode());
	}
}
</pre>
<h3>11.2. Generic DAOs</h3>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.dao;

public interface GenericDao&lt;E, K&gt;
{
	E find(K id);

	void persist(E e);

	void remove(E e);
}
</pre>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.dao;

import java.lang.reflect.ParameterizedType;

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

public abstract class AbstractGenericDao&lt;E, K&gt; implements GenericDao&lt;E, K&gt;
{
	private Class&lt;E&gt; classType;

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

	@SuppressWarnings(&quot;unchecked&quot;)
	public AbstractGenericDao()
	{
		ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
		classType = (Class&lt;E&gt;) parameterizedType.getActualTypeArguments()[0];
	}

	protected final EntityManager getEntityManager()
	{
		if (null == entityManager)
		{
			throw new IllegalStateException(&quot;EntityManager is not injected.&quot;);
		}
		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);
	}
}
</pre>
<pre class="brush: java; title: ; notranslate">
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&lt;User, Long&gt;
{
	List&lt;User&gt; getUsersByGivenName(String givenName);
}
</pre>
<pre class="brush: java; title: ; notranslate">
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&lt;User, Long&gt; implements UserDao
{
	@SuppressWarnings(&quot;unchecked&quot;)
	@Override
	public List&lt;User&gt; getUsersByGivenName(String givenName)
	{
		return getEntityManager().createQuery(&quot;from User where givenName = ?&quot;)
				.setParameter(1, givenName)
				.getResultList();
	}
}
</pre>
<h3>11.3. Services</h3>
<pre class="brush: java; title: ; notranslate">
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&lt;User&gt; getUserByGivenName(String givenName);
}
</pre>
<pre class="brush: java; title: ; notranslate">
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&lt;User&gt; getUserByGivenName(String givenName)
	{
		return userDao.getUsersByGivenName(givenName);
	}

}
</pre>
<h3>11. 4. Servlets</h3>
<pre class="brush: java; title: ; notranslate">
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(&quot;kevinlee&quot;);
		user.setSurname(&quot;Lee&quot;);
		user.setGivenName(&quot;Kevin&quot;);
		user.setEmail(&quot;test@test.test&quot;);

		userService.AddUser(user);

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

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

}
</pre>
<h3>11.5. Deployment Descriptor (web.xml)</h3>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
	&lt;display-name&gt;test-web-hibernate&lt;/display-name&gt;
	&lt;servlet&gt;
		&lt;description&gt;&lt;/description&gt;
		&lt;display-name&gt;TestServlet&lt;/display-name&gt;
		&lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;com.lckymn.kevin.test.openejb.web.TestServlet&lt;/servlet-class&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/Test&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
	&lt;welcome-file-list&gt;
		&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
	&lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>
<h3>11. 6. index.jsp</h3>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
	&lt;table&gt;
		&lt;tr&gt;
			&lt;td&gt;User ID: &lt;/td&gt;&lt;td&gt;${user.id }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Username: &lt;/td&gt;&lt;td&gt;${user.username }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Surname: &lt;/td&gt;&lt;td&gt;${user.surname }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Given name: &lt;/td&gt;&lt;td&gt;${user.givenName }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Email: &lt;/td&gt;&lt;td&gt;${user.email }&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>12. Run the test application</h2>
<p>Access the application URI</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">

http://localhost:8080/test-web-hibernate/Test
</pre>
<p>It gives me this result.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
User ID: 	1
Username: 	kevinlee
Surname: 	Lee
Given name: 	Kevin
Email: 	test@test.test
</pre>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
*** Important ***<br />
Note: Whenever you make changes in your application, Tomcat restarts the application context so that you don&#8217;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.
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

