<?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>ViralPatel.net &#187; JavaEE</title> <atom:link href="http://viralpatel.net/blogs/category/j2ee/feed" rel="self" type="application/rss+xml" /><link>http://viralpatel.net/blogs</link> <description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description> <lastBuildDate>Tue, 24 Jan 2012 13:45:10 +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>Play Framework Modules: Divide and Conquer</title><link>http://viralpatel.net/blogs/2012/01/play-framework-modules.html</link> <comments>http://viralpatel.net/blogs/2012/01/play-framework-modules.html#comments</comments> <pubDate>Tue, 03 Jan 2012 18:52:03 +0000</pubDate> <dc:creator>Sebastian Scarano</dc:creator> <category><![CDATA[JavaEE]]></category> <category><![CDATA[Play Framework]]></category> <category><![CDATA[Play-framework]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2581</guid> <description><![CDATA[It&#8217;s usually the case that you start developing an application and go on fulfilling requirements. When your application grows bigger you start to realize the convenience of separating it into different components. Moreover, when you develop your second or third application, your begin to recognize certain features that could be reused across different applications. These [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2011/01/Play-framework.png" alt="Play-framework" title="Play-framework" width="200" height="79" class="alignleft size-full wp-image-2136" />It&#8217;s usually the case that you start developing an application and go on fulfilling requirements. When your application grows bigger you start to realize the convenience of separating it into different components. Moreover, when you develop your second or third application, your begin to recognize certain features that could be reused across different applications.</p><p>These are two good reasons to modularize an application. Ideally we should aim at components with high <a rel="nofollow" title="Cohesion" href="http://en.wikipedia.org/wiki/Cohesion_(computer_science)">cohesion</a> and low <a rel="nofollow" title="Coupling" href="http://en.wikipedia.org/wiki/Coupling_(computer_science)">coupling</a>.</p><p>The Java language has proven itself quite fit to accomplish this kind of tasks. It provides general means to enforce the use of well defined API thru interfaces, abstract classes, etc.</p><p>Play framework developers think that this is perfectly fine for developing a general purpose library, but in the case of a web application reusability and modularization could be best achieved by other means. Have a look at this excerpt taken from <a rel="nofollow" href="http://www.playframework.org/documentation/latest/faq#aYouguysdontevenknowhowtoprograminJava...a">play framework&#8217;s FAQ</a>:</p><blockquote><p>Java itself is a very generic programming language and not originally designed for web application development. It is a very different thing to write a generic and reusable Java library and to create a web application. A web application itself doesn’t need to be designed to be reusable. You need less abstraction, less configuration. Reusability does exist for web applications, but through web service APIs rather than language-level integration.</p></blockquote><p>So when it comes to reusability, play provides us with a solution better suited for web applications.</p><h2>Play modules</h2><p>A <a rel="nofollow" href="http://www.playframework.org/documentation/latest/modules#what">module</a> is just another Play framework application. The only difference is that a module is not meant to be run on his own, it needs to be included into a containing application.</p><p>Nevertheless, there area a couple of differences between a module and a regular application, mainly that a module has no conf file (it has to be provided by the main application) and everything in a module is optional.</p><p>Doing is better than saying, so as usual we will look for a fine opportunity to make a simple module to show how it works.</p><h2>Creating a new play framework application and deploying it to the cloud</h2><p>As many of you already know, we are working on the <a rel="nofollow" href="http://playdoces.appspot.com/">spanish translation of play framework site</a>. We wanted to add web analytics to it so that we can see how people were using it.</p><p>So in order to follow this example, we&#8217;ll need a play framework app deployed somewhere on the Internet. Nowadays there are lots of Java hosting options available for free. Here you have a couple of tutorials for deploying on <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-12.5---deploy-to-openshift">openshift</a>, <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-14---deploy-to-gae">google application engine</a> and <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-13---deploy-to-heroku">heroku</a>.</p><p>First let&#8217;s create a play framework application, I&#8217;ll create the app at ~/devel/apps/module-test, you can choose whatever location you like, just be sure to update the commands appropriately.</p><p>To create the app, run the following command at an os prompt:</p><p><pre class="brush: plain; title: ; notranslate">
sas@ubuntu:~/devel/apps/module-test$ play new analytics-app
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~
~ play! 1.2.4, http://www.playframework.org
~
~ The new application will be created in /home/sas/Dropbox/Public/devel/play/apps/module-test/analytics-app
~ What is the application name? [analytics-app]
~
~ OK, the application is created.
~ Start it with : play run analytics-app
~ Have fun!
</pre><p>Now it would be a good time to deploy it somewhere. For this tutorial we will deploy it at openshift, you can use any host you want (For more information on setting up your environment for openshift deployment follow <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-12.5---deploy-to-openshift">this tutorial</a>)</p><p>Create a new directory at ~/devel/apps/module-test/openshift, go to that directory and run:</p><pre class="brush: plain; title: ; notranslate">
rhc-create-app -l mymail@mail.com -p mypassword -t jbossas-7.0 -a analyticsapp

Attempting to create remote application space: analyticsapp
Now your new domain name is being propagated worldwide (this might take a minute)...
Pulling new repo down

[...]

Successfully created application: analyticsapp
</pre><p>Next, we&#8217;ll get rid of the demo app:</p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/openshift/analyticsapp
rm -fr pom.xml src
</pre><p>And we&#8217;ll compile and package the newly created app as an exploded war. Go to ~/devel/apps/module-test folder and run:</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test
play war analytics-app -o openshift/analyticsapp/deployments/ROOT.war
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~
~ play! 1.2.4, http://www.playframework.org
~
JPDA port 8000 is already used. Will try to use any free port for debugging
Listening for transport dt_socket at address: 53978
00:22:38,021 INFO  ~ Starting /home/sas/Dropbox/Public/devel/play/apps/module-test/analytics-app
00:22:39,891 INFO  ~ Precompiling ...
00:22:49,075 INFO  ~ Done.
~ Packaging current version of the framework and the application to /home/sas/Dropbox/Public/devel/play/apps/module-test/openshift/analyticsapp/deployments/ROOT.war ...
~ Done !
~
~ You can now load /home/sas/Dropbox/Public/devel/play/apps/module-test/openshift/analyticsapp/deployments/ROOT.war as a standard WAR into your servlet container
~ You can't use play standard commands to run/stop/debug the WAR application...
~ ... just use your servlet container commands instead
~
~ Have fun!
~
</pre></p><p>Now we just need to commit the application and push it to our git repo on openshift:</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/openshift/analyticsapp
touch deployments/ROOT.war.dodeploy
git add -A
git commit -m &quot;deploy play framework app&quot;
git push origin
</pre></p><p><em>Note: The first time it will take a couple of minutes to push the application, because of play framework libraries. Later pushes will be much quicker, git is smart enough to only send updated files.</em></p><p>And that&#8217;s it, you&#8217;ve just deployed your first app to red hat&#8217;s cloud. You can see it running at http://analyticsapp-opensas.rhcloud.com/ (of course, you&#8217;ll have to replace &#8220;opensas&#8221; with your own openshift user name).</p><h2>Google web analytics &#038; play framework</h2><p>Adding Google web analytics to a play app is really easy. You just need a gmail account, then go to <a rel="nofollow" href="http://www.google.com/analytics/">Google Analytics web site</a>, click on &#8220;sign up&#8221;, login with your gmail account, and complete all the required data.</p><p>In the account name enter &#8220;analytics-app&#8221;, in the website&#8217;s url enter http://analyticsapp-opensas.rhcloud.com, agree to the terms and conditions and click on &#8220;Create account&#8221;.</p><p>You&#8217;ll be taken to your analytics-app account page, there you can see the tracking code. You&#8217;ll just have to paste it in your app. So open the file at ~/devel/apps/module-test/analytics-app/app/views/main.html and paste the tracking code before the closing head tag, like this:</p><pre class="brush: jscript; title: ; notranslate">
[...]
        &lt;script src=&quot;@{'/public/javascripts/jquery-1.6.4.min.js'}&quot; type=&quot;text/javascript&quot; charset=&quot;${_response_encoding}&quot;&gt;&lt;/script&gt;
        #{get 'moreScripts' /}

&lt;script type=&quot;text/javascript&quot;&gt;

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

&lt;/script&gt;

    &lt;/head&gt;
    &lt;body&gt;
[...]
</pre><p><em>Note: Google will provide you with your own UA-XXXXXXXX-1 account code, so just copy and paste the code from your Google analytics account page, and NOT from this page!</em></p><p>Now you just have to generate the war folder, commit, and push it once again to openshift to deploy your changes. Every time you make a change you&#8217;ll have to follow these same steps to deploy it to openshift.</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test
play war analytics-app/ -o openshift/analyticsapp/deployments/ROOT.war
cd openshift/analyticsapp/
git add -A
git commit -m &quot;added tracking code&quot;
git push origin
</pre></p><p>Visit again your page at http://analyticsapp-opensas.rhcloud.com/, and see the source of the page to check that the tracking code has been added. You can also see it in action on Google&#8217;s analytics page, click on &#8220;Home&#8221;, Real-Time (BETA), and the Overview. You should have one visitor (yes, it&#8217;s you!).</p><p>So far now we created a new play application and deployed it to openshift. Then we created a Google analytic account and added the tracking code the our play application. Everything is working ok and our app is being tracked by Google. Now we are going to move that functionality to a module so that we can reuse it from other apps.</p><h2>Creating a module</h2><p>To create a new module you have to use the &#8220;new-module&#8221; play command, like this:</p><p><pre class="brush: plain; title: ; notranslate">
cd /home/sas/devel/apps/module-test/
play new-module analytics
</pre></p><p>Now, in order to tell our main application (in our case analytics-app) to include this module, we have to configure a <a rel="nofollow" href="http://www.playframework.org/documentation/latest/dependency#Localrepositories">local repository</a>.</p><p>Edit ~/devel/apps/module-test/analytics-app/conf/dependencies.yml like this:</p><p><pre class="brush: plain; title: ; notranslate">
# Application dependencies

require:
    - play
    - analytics -&gt; analytics

repositories:
    - My local modules:
        type:       local
        artifact:   ${application.path}/../[module]
        contains:
            - analytics
</pre></p><p>and after that run the following command to tell play to resolve dependencies.</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/analytics-app
play dependencies
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~
~ play! 1.2.4, http://www.playframework.org
~
~ Resolving dependencies using /home/sas/devel/apps/module-test/analytics-app/conf/dependencies.yml,
~
~ 	analytics-&gt;analytics -&gt; (from My local modules)
~
~ Installing resolved dependencies,
~
~ 	modules/analytics -&gt; /home/sas/devel/apps/module-test/analytics/../analytics
~
~ Done!
~
</pre></p><p>You can now start the main application on your workstation:</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/analytics-app
play run
</pre></p><p>You can see your app running at <a rel="nofollow" href="http://localhost:9000">http://localhost:9000</a>.</p><h2>Moving the tracking code to a reusable tag</h2><p>Now we will move the tracking code to a tag defined in the module, so we&#8217;ll create a file ~/devel/apps/module-test/analytics/app/views/analytics.html with the tracking code, like this:</p><pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

&lt;/script&gt;
</pre><p>And now, replace the tracking code in main.html with a call to the tag, like this:</p><pre class="brush: jscript; title: ; notranslate">
[...]
        &lt;script src=&quot;@{'/public/javascripts/jquery-1.6.4.min.js'}&quot; type=&quot;text/javascript&quot; charset=&quot;${_response_encoding}&quot;&gt;&lt;/script&gt;

        #{get 'moreScripts' /}

#{analytics /}
    &lt;/head&gt;
[...]
</pre><h2>Getting module configuration from the application.conf file</h2><p>Our module is almost ready, there&#8217;s just one thing that&#8217;s preventing us from really reusing it on another application: the Google analytics code is hardcoded in our tag!</p><p>So we will read it from the application.conf file. Just edit the analytics.html tag like this:</p><pre class="brush: jscript; title: ; notranslate">
%{
    String code = play.Play.configuration.getProperty(&quot;analytics.code&quot;, &quot;&quot;)
}%
#{if code!=&quot;&quot;}

&lt;script type=&quot;text/javascript&quot;&gt;
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '${code}}']);
  _gaq.push(['_trackPageview']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
&lt;/script&gt;
#{/if}
</pre><p>and add the following to your main application configuration file at ~/devel/apps/module-test/analytics-app/conf/application.conf</p><pre class="brush: jscript; gutter: false; title: ; notranslate">
analytics.code=UA-XXXXXXXX-1
</pre><h2>Prevent tracking in dev mode</h2><p>This tag will will update the tracker every time the page is rendered, even when we are working on our development workstation!</p><p>So we will add a minor improvement to prevent the module from logging the page activity while working in development mode.</p><p>Just add the following condition to the code:</p><pre class="brush: plain; title: ; notranslate">
%{
    String code = play.Play.configuration.getProperty(&quot;analytics.code&quot;, &quot;&quot;)
}%
#{if play.mode.isProd() &amp;&amp; code!=&quot;&quot;}
&lt;script type=&quot;text/javascript&quot;&gt;

  var _gaq = _gaq || [];
[...]
</pre><h2>Troubleshooting Openshift</h2><p>Openshift won&#8217;t be able to resolve the relative reference to the module location (and in fact any war deployed application will have the same problem), so you&#8217;ll have to tell play to copy the module sources to the containing application before generating the war folder. Just issue:</p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/analytics-app
play dependencies --forceCopy
</pre><p>And that&#8217;s it, now you can deploy to openshift in the usual way:</p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test
play war analytics-app/ -o openshift/analyticsapp/deployments/ROOT.war
cd openshift/analyticsapp/
git add -A
git commit -m &quot;added analytics module&quot;

git push origin
</pre><p>Run your site locally with &#8220;play run&#8221;, and also open it from <a rel="nofollow" href="http://analyticsapp-opensas.rhcloud.com/">http://analyticsapp-opensas.rhcloud.com/</a>, check the source code of both sites, you should see that the app running at openshift contains the tracking code, contrary to your local application.</p><h2>Conclusion</h2><p>In this post we saw how to deploy a play framework app to openshift and, more important, how to move features from your application to a module in order to reuse it from other applications.</p><p>You can learn more about modules on <a rel="nofollow" href="http://playframework.wordpress.com/2011/02/27/play-modules/">this article</a> or reading the <a rel="nofollow" href="http://www.playframework.org/documentation/latest/modules">play framework documentation</a>.</p><p>If you speak spanish you can <a rel="nofollow" href="http://playdoces.appspot.com/documentation/latest/translation">help us with the translation</a>, and you can also have a look at our work right <a rel="nofollow" href="http://playdoces.appspot.com/documentation/latest/modules">here</a>&#8230; You can be sure every click you make will be tracked!</p><p><i>From: <a rel="nofollow" href="http://playlatam.wordpress.com">http://playlatam.wordpress.com</a></i></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/01/first-play-framework-gae-siena-application-tutorial-example.html" title="Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example">Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/play-framework-modules.html/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Hibernate Inheritance: Table Per Concrete Class (Annotation &amp; XML mapping)</title><link>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html#comments</comments> <pubDate>Fri, 30 Dec 2011 12:45:45 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[annotation]]></category> <category><![CDATA[hibernate-architecture]]></category> <category><![CDATA[xml]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2509</guid> <description><![CDATA[Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table per Subclass. Today we will see how to implement Hibernate Inheritance: One Table per Concrete Class scheme. You may want to look at previous tutorials. Here is the complete list for you. Introduction to Inheritance in Hibernate [...]]]></description> <content:encoded><![CDATA[<p>Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table per Subclass.</p><p>Today we will see how to implement Hibernate Inheritance: One Table per Concrete Class scheme.</p><p>You may want to look at previous tutorials. Here is the complete list for you.</p><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div><p><br/></p><h2>Introduction to Inheritance in Hibernate</h2><p>Java is an object oriented language. It is possible to implement Inheritance in Java. Inheritance is one of the most visible facets of Object-relational mismatch. Object oriented systems can model both <strong>&#8220;is a&#8221;</strong> and <strong>&#8220;has a&#8221;</strong> relationship. Relational model supports only &#8220;has a&#8221; relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs.</p><h2>One Table per Concrete Class example</h2><p>Suppose we have a class Person with subclasses Employee and Owner. Following the class diagram and relationship of these classes.</p><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-subclass-class-diagram-uml.png" alt="hibernate-table-per-subclass-class-diagram-uml" title="hibernate-table-per-subclass-class-diagram-uml" width="350" height="193" class="aligncenter size-full wp-image-2481" /></p><p>In One Table per Concrete class scheme, each concrete class is mapped as normal persistent class. Thus we have 3 tables; PERSON, EMPLOYEE and OWNER to persist the class data. In this scheme, the mapping of the subclass repeats the properties of the parent class.</p><p>Following are the advantages and disadvantages of One Table per Subclass scheme.</p><h4>Advantages</h4><ul><li>This is the easiest method of Inheritance mapping to implement.</li></ul><h4>Disadvantages</h4><ul><li>Data thats belongs to a parent class is scattered across a number of subclass tables, which represents concrete classes.</li><li>This hierarchy is not recommended for most cases.</li><li>Changes to a parent class is reflected to large number of tables</li><li>A query couched in terms of parent class is likely to cause a large number of select operations</li></ul><p>This strategy has many drawbacks (esp. with polymorphic queries and associations) explained in the JPA spec, the Hibernate reference documentation, Hibernate in Action, and many other places. Hibernate work around most of them implementing this strategy using SQL UNION queries. It is commonly used for the top level of an inheritance hierarchy:</p><h2>Create Database Table to persist Concrete classes</h2><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `person` (
	`person_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL DEFAULT '0',
	`lastname` VARCHAR(50) NOT NULL DEFAULT '0',
	PRIMARY KEY (`person_id`)
)

CREATE TABLE `employee` (
	`person_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL,
	`lastname` VARCHAR(50) NOT NULL,
	`joining_date` DATE NULL DEFAULT NULL,
	`department_name` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`)
)

CREATE TABLE `owner` (
	`person_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL DEFAULT '0',
	`lastname` VARCHAR(50) NOT NULL DEFAULT '0',
	`stocks` BIGINT(11) NULL DEFAULT NULL,
	`partnership_stake` BIGINT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`)
)
</pre><p><br/></p><h2>Project Structure in Eclipse</h2><h4>For XML mapping</h4><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-concrete-class-xml-project-structure.png" alt="hibernate-table-per-concrete-class-xml-project-structure" title="hibernate-table-per-concrete-class-xml-project-structure" width="262" height="343" class="aligncenter size-full wp-image-2512" /></p><h4>For Annotation mapping</h4><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-concrete-class-annotation-project-structure.png" alt="hibernate-table-per-concrete-class-annotation-project-structure" title="hibernate-table-per-concrete-class-annotation-project-structure" width="263" height="325" class="aligncenter size-full wp-image-2513" /><br /> <br/></p><h2>Hibernate Inheritance: XML Mapping</h2><p>Following is the example where we map Person, Employee and Owner entity classes using XML mapping.</p><p><em>File: Person.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Person {

	private Long personId;
	private String firstname;
	private String lastname;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Employee.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

public class Employee extends Person {

	private Date joiningDate;
	private String departmentName;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Owner extends Person {

		private Long stocks;
		private Long partnershipStake;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Person.hbm.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Person&quot; table=&quot;PERSON&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;

	&lt;/class&gt;

	&lt;class name=&quot;Employee&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;
		&lt;property name=&quot;departmentName&quot; column=&quot;department_name&quot; /&gt;
		&lt;property name=&quot;joiningDate&quot; type=&quot;date&quot; column=&quot;joining_date&quot; /&gt;
	&lt;/class&gt;

	&lt;class name=&quot;Owner&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;
		&lt;property name=&quot;stocks&quot; column=&quot;stocks&quot; /&gt;
		&lt;property name=&quot;partnershipStake&quot; column=&quot;partnership_stake&quot; /&gt;
	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p><br/></p><p>Note that we have defined only one hibernate mapping (hbm) file <code>Person.hbm.xml</code>. Both <code>Person</code> and <code>Employee</code> model class are defined within one hbm file.</p><p>We mapped all the classes using simple &lt;class&gt; tag in hbm. This is the usual way of mapping classes in XML.</p><h2>Hibernate Inheritance: Annotation Mapping</h2><p>Following is the example where we map Person, Employee and Owner entity classes using JPA Annotations.</p><p><em>File: Person.java</em></p><pre class="brush: java; highlight: [12]; title: ; notranslate">
package net.viralpatel.hibernate;

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

@Entity
@Table(name = &quot;PERSON&quot;)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person {

	@Id
	@Column(name = &quot;PERSON_ID&quot;)
	private Long personId;

	@Column(name = &quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name = &quot;LASTNAME&quot;)
	private String lastname;

	public Person() {

	}
	public Person(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}
	// Getter and Setter methods,
}
</pre><p><br/></p><p><strong><code>@Inheritance</code></strong> &#8211; Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.</p><p><strong><code>@InheritanceType</strong></code> &#8211; Defines inheritance strategy options. TABLE_PER_CLASS is a strategy to map table per concrete class.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [13,14,15,16]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
@AttributeOverrides({
    @AttributeOverride(name=&quot;firstname&quot;, column=@Column(name=&quot;FIRSTNAME&quot;)),
    @AttributeOverride(name=&quot;lastname&quot;, column=@Column(name=&quot;LASTNAME&quot;))
})
public class Employee extends Person {

	@Column(name=&quot;joining_date&quot;)
	private Date joiningDate;

	@Column(name=&quot;department_name&quot;)
	private String departmentName;

	public Employee() {
	}

	public Employee(String firstname, String lastname, String departmentName, Date joiningDate) {

		super(firstname, lastname);

		this.departmentName = departmentName;
		this.joiningDate = joiningDate;
	}

	// Getter and Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; highlight: [11,12,13,14]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name=&quot;OWNER&quot;)
@AttributeOverrides({
    @AttributeOverride(name=&quot;firstname&quot;, column=@Column(name=&quot;FIRSTNAME&quot;)),
    @AttributeOverride(name=&quot;lastname&quot;, column=@Column(name=&quot;LASTNAME&quot;))
})
public class Owner extends Person {

	@Column(name=&quot;stocks&quot;)
	private Long stocks;

	@Column(name=&quot;partnership_stake&quot;)
	private Long partnershipStake;

	public Owner() {
	}

	public Owner(String firstname, String lastname, Long stocks, Long partnershipStake) {

		super(firstname, lastname);

		this.stocks = stocks;
		this.partnershipStake = partnershipStake;
	}

	// Getter and Setter methods,
}
</pre><p><br/></p><p>Both Employee and Owner classes are child of Person class. Thus while specifying the mappings, we used <code>@AttributeOverrides</code> to map them.</p><p><strong><code>@AttributeOverrides</strong></code> &#8211; This annotation is used to override mappings of multiple properties or fields.</p><p><strong><code>@AttributeOverride</strong></code> &#8211; The AttributeOverride annotation is used to override the mapping of a Basic (whether explicit or default) property or field or Id property or field.</p><p>The AttributeOverride annotation may be applied to an entity that extends a mapped superclass or to an embedded field or property to override a basic mapping defined by the mapped superclass or embeddable class. If the AttributeOverride annotation is not specified, the column is mapped the same as in the original mapping.</p><p>Thus in over case, firstname and lastname are defined in parent class Person and mapped in child class Employee and Owner using @AttributeOverrides annotation.</p><p>This strategy supports one-to-many associations provided that they are bidirectional. This strategy does not support the IDENTITY generator strategy: the id has to be shared across several tables. Consequently, when using this strategy, you should not use AUTO nor IDENTITY. Note that in below Main class we specified the primary key explicitly.</p><h2>Main class</h2><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Person person = new Person(&quot;Steve&quot;, &quot;Balmer&quot;);
		person.setPersonId(1L);
		session.save(person);

		Employee employee = new Employee(&quot;James&quot;, &quot;Gosling&quot;, &quot;Marketing&quot;, new Date());
		employee.setPersonId(2L);
		session.save(employee);

		Owner owner = new Owner(&quot;Bill&quot;, &quot;Gates&quot;, 300L, 20L);
		owner.setPersonId(3L);
		session.save(owner);

		session.getTransaction().commit();
		session.close();

	}
}
</pre><p>The Main class is used to persist <code>Person</code>, <code>Employee</code> and <code>Owner</code> object instances. Note that these classes are persisted in different tables and parent attributes (firstname, lastname) are repeated across all tables.</p><h4>Output</h4><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into PERSON (FIRSTNAME, LASTNAME, PERSON_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, department_name, joining_date, PERSON_ID) values (?, ?, ?, ?, ?)
Hibernate: insert into OWNER (FIRSTNAME, LASTNAME, partnership_stake, stocks, PERSON_ID) values (?, ?, ?, ?, ?)
</pre><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-concrete-class-output.png" alt="hibernate-table-per-concrete-class-output" title="hibernate-table-per-concrete-class-output" width="459" height="204" class="aligncenter size-full wp-image-2511" /></p><p><br/></p><h2>Download Source Code</h2><p><em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-concrete-class_xml.zip">Hibernate-inheritance-table-per-concrete-class_xml.zip (9 KB)</a></em><br /> <em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-concrete-class_annotation.zip">Hibernate-inheritance-table-per-concrete-class_annotation.zip (9 KB)</a></em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html" title="Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)">Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html" title="Hibernate Self Join Annotations One To Many mapping example">Hibernate Self Join Annotations One To Many mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Hibernate Inheritance: Table Per Subclass (Annotation &amp; XML mapping)</title><link>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html#comments</comments> <pubDate>Tue, 27 Dec 2011 09:40:15 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[hibernate-architecture]]></category> <category><![CDATA[hibernate-configuration]]></category> <category><![CDATA[Inheritance]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2479</guid> <description><![CDATA[Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table Per Hierarchy. Today we will see how to implement Hibernate Inheritance: One Table per Subclass scheme. You may want to look at previous tutorials. Here is the complete list for you. Introduction to Inheritance in Hibernate Java [...]]]></description> <content:encoded><![CDATA[<p>Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table Per Hierarchy.</p><p>Today we will see how to implement Hibernate Inheritance: One Table per Subclass scheme.</p><p>You may want to look at previous tutorials. Here is the complete list for you.</p><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div><p><br/></p><h2>Introduction to Inheritance in Hibernate</h2><p>Java is an object oriented language. It is possible to implement Inheritance in Java. Inheritance is one of the most visible facets of Object-relational mismatch. Object oriented systems can model both <strong>&#8220;is a&#8221;</strong> and <strong>&#8220;has a&#8221;</strong> relationship. Relational model supports only &#8220;has a&#8221; relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs.</p><h2>One Table Per Subclass example</h2><p>Suppose we have a class Person with subclass Employee and Owner. Following the class diagram and relationship of these classes.</p><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-subclass-class-diagram-uml.png" alt="hibernate-table-per-subclass-class-diagram-uml" title="hibernate-table-per-subclass-class-diagram-uml" width="350" height="193" class="aligncenter size-full wp-image-2481" /></p><p>In One Table per Subclass scheme, each class persist the data in its own separate table. Thus we have 3 tables; PERSON, EMPLOYEE and OWNER to persist the class data. Note that a foreign key relationship exists between the subclass tables and super class table. Thus the common data is stored in PERSON table and subclass specific fields are stored in EMPLOYEE and OWNER tables.</p><p>Following are the advantages and disadvantages of One Table per Subclass scheme.</p><h4>Advantage</h4><ul><li>Using this hierarchy, does not require complex changes to the database schema when a single parent class is modified.</li><li>It works well with shallow hierarchy.</li></ul><h4>Disadvantage</h4><ul><li>As the hierarchy grows, it may result in poor performance.</li><li>The number of joins required to construct a subclass also grows.</li></ul><h2>Create Database Table to persist Subclass</h2><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `person` (
	`person_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL DEFAULT '0',
	`lastname` VARCHAR(50) NOT NULL DEFAULT '0',
	PRIMARY KEY (`person_id`)
)

CREATE TABLE `employee` (
	`person_id` BIGINT(10) NOT NULL,
	`joining_date` DATE NULL DEFAULT NULL,
	`department_name` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`),
	CONSTRAINT `FK_PERSON` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
)

CREATE TABLE `owner` (
	`person_id` BIGINT(20) NOT NULL DEFAULT '0',
	`stocks` BIGINT(11) NULL DEFAULT NULL,
	`partnership_stake` BIGINT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`),
	CONSTRAINT `FK_PERSON2` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
)
</pre><p><br/></p><h2>Hibernate Inheritance: XML Mapping</h2><p>Following is the example where we map Person, Employee and Owner entity classes using XML mapping.</p><p><em>File: Person.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Person {

	private Long personId;
	private String firstname;
	private String lastname;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Employee.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

public class Employee extends Person {

	private Date joiningDate;
	private String departmentName;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Owner extends Person {

		private Long stocks;
		private Long partnershipStake;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Person.hbm.xml</em></p><pre class="brush: java; highlight: [16,21]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Person&quot; table=&quot;PERSON&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;

		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;

		&lt;joined-subclass name=&quot;Employee&quot; extends=&quot;Person&quot;&gt;
				&lt;key column=&quot;person_id&quot; /&gt;
				&lt;property name=&quot;departmentName&quot; column=&quot;department_name&quot; /&gt;
				&lt;property name=&quot;joiningDate&quot; type=&quot;date&quot; column=&quot;joining_date&quot; /&gt;
		&lt;/joined-subclass&gt;
		&lt;joined-subclass name=&quot;Owner&quot; extends=&quot;Person&quot;&gt;
				&lt;key column=&quot;person_id&quot; /&gt;
				&lt;property name=&quot;stocks&quot; column=&quot;stocks&quot; /&gt;
				&lt;property name=&quot;partnershipStake&quot; column=&quot;partnership_stake&quot; /&gt;
		&lt;/joined-subclass&gt;
	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p><br/></p><p>Note that we have defined only one hibernate mapping (hbm) file <code>Person.hbm.xml</code>. Both <code>Person</code> and <code>Employee</code> model class are defined within one hbm file.</p><p><strong>&lt;discriminator&gt;</strong> tag is used to define the discriminator column.</p><p><strong>&lt;subclass&gt;</strong> tag is used to map the subclass Employee. Note that we have not used the usual <code>&lt;class&gt;</code> tag to map Employee as it falls below in the hierarchy tree.</p><p>The discriminator-value for <code>Person</code> is defined as <em>&#8220;P&#8221;</em> and that for <code>Employee</code> is defined <em>&#8220;E&#8221;</em>, Thus, when Hibernate will persist the data for person or employee it will accordingly populate this value.</p><h2>Hibernate Inheritance: Annotation Mapping</h2><p>Following is the example where we map Employee and Person entity classes using JPA Annotations.</p><p><em>File: Person.java</em></p><pre class="brush: java; highlight: [13]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name = &quot;PERSON&quot;)
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {

	@Id
	@GeneratedValue
	@Column(name = &quot;PERSON_ID&quot;)
	private Long personId;

	@Column(name = &quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name = &quot;LASTNAME&quot;)
	private String lastname;

	public Person() {

	}
	public Person(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}

	// Getter and Setter methods,
}
</pre><p><br/></p><p>The <code>Person</code> class is the root of hierarchy. Hence we have used some annotations to make it as the root.</p><p><strong><code>@Inheritance</code></strong> &#8211; Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.</p><p><strong><code>@InheritanceType</strong></code> &#8211; Defines inheritance strategy options. JOINED is a strategy in which fields that are specific to a subclass are mapped to a separate table than the fields that are common to the parent class, and a join is performed to instantiate the subclass. Thus fields of Employee (joining_date, department) and Owner (stocks etc) are mapped to their respective tables.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [12]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

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

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
@PrimaryKeyJoinColumn(name=&quot;PERSON_ID&quot;)
public class Employee extends Person {

	@Column(name=&quot;joining_date&quot;)
	private Date joiningDate;

	@Column(name=&quot;department_name&quot;)
	private String departmentName;

	public Employee() {
	}

	public Employee(String firstname, String lastname, String departmentName, Date joiningDate) {

		super(firstname, lastname);

		this.departmentName = departmentName;
		this.joiningDate = joiningDate;
	}

	// Getter and Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; highlight: [10]; title: ; notranslate">
package net.viralpatel.hibernate;

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

@Entity
@Table(name=&quot;OWNER&quot;)
@PrimaryKeyJoinColumn(name=&quot;PERSON_ID&quot;)
public class Owner extends Person {

	@Column(name=&quot;stocks&quot;)
	private Long stocks;

	@Column(name=&quot;partnership_stake&quot;)
	private Long partnershipStake;

	public Owner() {
	}

	public Owner(String firstname, String lastname, Long stocks, Long partnershipStake) {

		super(firstname, lastname);

		this.stocks = stocks;
		this.partnershipStake = partnershipStake;
	}

	// Getter and Setter methods,
}
</pre><p><br/></p><p>Both Employee and Owner classes are child of Person class. Thus while specifying the mappings, we used <code>@PrimaryKeyJoinColumn</code> to map it to parent table.</p><p><strong><code>@PrimaryKeyJoinColumn</strong></code> &#8211; This annotation specifies a primary key column that is used as a foreign key to join to another table.</p><p>It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.</p><p>If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass</p><h2>Main class</h2><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Person person = new Person(&quot;Steve&quot;, &quot;Balmer&quot;);
		session.save(person);

		Employee employee = new Employee(&quot;James&quot;, &quot;Gosling&quot;, &quot;Marketing&quot;, new Date());
		session.save(employee);

		Owner owner = new Owner(&quot;Bill&quot;, &quot;Gates&quot;, 300L, 20L);
		session.save(owner);

		session.getTransaction().commit();
		session.close();

	}
}
</pre><p>The Main class is used to persist <code>Person</code>, <code>Employee</code> and <code>Owner</code> object instances. Note that these classes are persisted in different tables.</p><h4>Output</h4><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into Employee (department_name, joining_date, person_id) values (?, ?, ?)
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into Owner (stocks, partnership_stake, person_id) values (?, ?, ?)
</pre><p><img src="http://img.viralpatel.net/2011/12/hibernate-inheritance-table-per-subclass-table-output.png" alt="hibernate-inheritance-table-per-subclass-table-output" title="hibernate-inheritance-table-per-subclass-table-output" width="314" height="240" class="aligncenter size-full wp-image-2496" /></p><p><br/></p><h2>Download Source Code</h2><p><em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-subclass_xml.zip">Hibernate-inheritance-table-per-subclass_xml.zip (9 KB)</a></em><br /> <em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-subclass_annotation.zip">Hibernate-inheritance-table-per-subclass_annotation.zip (9 KB)</a></em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html" title="Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)">Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html" title="Introduction to Hibernate framework">Introduction to Hibernate framework</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Struts 2 Tip: Override Default Theme</title><link>http://viralpatel.net/blogs/2011/12/struts-2-override-default-theme.html</link> <comments>http://viralpatel.net/blogs/2011/12/struts-2-override-default-theme.html#comments</comments> <pubDate>Wed, 21 Dec 2011 12:07:40 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Struts 2]]></category> <category><![CDATA[Struts2]]></category> <category><![CDATA[struts2-series]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2465</guid> <description><![CDATA[Recently I came up with a requirement in Struts 2 to display a particular form with some style and alignment. While creating the form the developer had used Struts 2&#8242;s taglib /struts-tags to paint the user controls like textboxes and select boxes. For example: Now it turns of that Struts 2 parse these s: tags [...]]]></description> <content:encoded><![CDATA[<p>Recently I came up with a requirement in Struts 2 to display a particular form with some style and alignment. While creating the form the developer had used Struts 2&#8242;s taglib <strong>/struts-tags</strong> to paint the user controls like textboxes and select boxes.</p><p>For example:</p><pre class="brush: xml; title: ; notranslate">
&lt;s:form action=&quot;add&quot; method=&quot;post&quot;&gt;
	&lt;s:textfield name=&quot;contact.firstName&quot; label=&quot;Firstname&quot;/&gt;
	&lt;s:textfield name=&quot;contact.lastName&quot; label=&quot;Lastname&quot;/&gt;
&lt;/s:form&gt;
</pre><p>Now it turns of that Struts 2 parse these <strong>s:</strong> tags and generate HTML tags like &lt;INPUT&gt; and &lt;SELECT&gt;. But Struts 2 not only generate these tags, but also generates enclosing &lt;TR&gt; tags to align them in a tabular format.</p><p>For example, the above Struts 2 code would generate HTML as following:</p><pre class="brush: xml; title: ; notranslate">
&lt;form id=&quot;add&quot; name=&quot;add&quot; action=&quot;add&quot; method=&quot;post&quot;&gt;
&lt;table class=&quot;wwFormTable&quot;&gt;
&lt;tr&gt;
    &lt;td class=&quot;tdLabel&quot;&gt;&lt;label for=&quot;add;contact_firstName&quot; class=&quot;label&quot;&gt;Firstname:&lt;/label&gt;&lt;/td&gt;
    &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;contact.firstName&quot; value=&quot;&quot; id=&quot;add;contact_firstName&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td class=&quot;tdLabel&quot;&gt;&lt;label for=&quot;add;contact_lastName&quot; class=&quot;label&quot;&gt;Lastname:&lt;/label&gt;&lt;/td&gt;
    &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;contact.lastName&quot; value=&quot;&quot; id=&quot;add;contact_lastName&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/form&gt;
</pre><p>Note how Struts2 taglib generated enclosing TR tags around the controls. Lets see why this is so.</p><h2>Themes in Struts 2</h2><p>When you use a Struts 2 tag such as <code>s:select</code> in your web page, the Struts 2 framework generates HTML that styles the appearance and controls the layout of the select control. The style and layout is determined by which Struts 2 theme is set for the tag. Struts 2 comes with three built-in themes: <strong>simple, xhtml, and css_xhtml</strong>. If you don’t specify a theme, then Struts 2 will use the <strong>xhtml theme</strong> by default.</p><p>Thus in our case, Struts 2 automatically rendered the controls using default <em>xhtml</em> theme.</p><h2>Specifying The Theme in Struts 2</h2><p>The Struts 2 tags have a theme attribute you can use to specify which Struts 2 theme should be used when creating the HTML for that tag. The values for the theme attribute are simple, xhtml, css_xhtml, and ajax.</p><p>You can specify the theme on a per Struts 2 tag basis or you can use one of the following methods to specify what theme Struts 2 should use:</p><ul><li>The theme attribute on the specific tag</li><li>The theme attribute on a tag&#8217;s surrounding form tag</li><li>The page-scoped attribute named &#8220;theme&#8221;</li><li>The request-scoped attribute named &#8220;theme&#8221;</li><li>The session-scoped attribute named &#8220;theme&#8221;</li><li>The application-scoped attribute named &#8220;theme&#8221;</li><li>The <strong><code>struts.ui.theme</code></strong> property in struts.properties (defaults to xhtml)</li></ul><p>Thus, you can specify what theme you want to use at any level. Tag level, enclosed tag lever, form level, page level or at application level.</p><p>I preferred specifying theme at the application level. To override the default scheme you can create (or update existing) struts.properties file in your project.</p><p>Create struts.properties file and add following line into it:</p><p><em>File: struts.properties</em></p><pre class="brush: xml; gutter: false; title: ; notranslate">
struts.ui.theme = css_xhtml
</pre><p>So if you want to take full control for your user interface and want to align all controls yourself, I would suggest you to use <strong>css_xhtml</strong> theme instead of default xhtml.</p><p>The theme for above JSP code when changed into css_xhtml would generate following HTML code.</p><pre class="brush: xml; title: ; notranslate">
&lt;form id=&quot;add&quot; name=&quot;add&quot; action=&quot;add&quot; method=&quot;post&quot;&gt;
	&lt;div id=&quot;wwgrp_add_contact_firstName&quot; class=&quot;wwgrp&quot;&gt;
		&lt;div id=&quot;wwlbl_add_contact_firstName&quot; class=&quot;wwlbl&quot;&gt;
		&lt;label for=&quot;add_contact_firstName&quot; class=&quot;label&quot;&gt;Firstname:&lt;/label&gt;
		&lt;/div&gt;
		&lt;br /&gt;
		&lt;div id=&quot;wwctrl_add_contact_firstName&quot; class=&quot;wwctrl&quot;&gt;
		&lt;input type=&quot;text&quot; name=&quot;contact.firstName&quot; value=&quot;&quot; id=&quot;add_contact_firstName&quot;/&gt;
		&lt;/div&gt;
	&lt;/div&gt;
	&lt;div id=&quot;wwgrp_add_contact_lastName&quot; class=&quot;wwgrp&quot;&gt;
		&lt;div id=&quot;wwlbl_add_contact_lastName&quot; class=&quot;wwlbl&quot;&gt;
		&lt;label for=&quot;add_contact_lastName&quot; class=&quot;label&quot;&gt;Lastname:&lt;/label&gt;
		&lt;/div&gt;
		&lt;br /&gt;
		&lt;div id=&quot;wwctrl_add_contact_lastName&quot; class=&quot;wwctrl&quot;&gt;
		&lt;input type=&quot;text&quot; name=&quot;contact.lastName&quot; value=&quot;&quot; id=&quot;add_contact_lastName&quot;/&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/form&gt;
</pre><p>So all we have to do is to write CSS style for classes like wwgrp, wwlbl, wwctrl etc.</p><p>Hope this helps. Please comment if you have some specific requirement or suggestions.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate">Writing a URL Shortner in Java Struts2 &#038; Hibernate</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/struts-2-override-default-theme.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Hibernate Inheritance: Table Per Class Hierarchy (Annotation &amp; XML Mapping)</title><link>http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html#comments</comments> <pubDate>Tue, 20 Dec 2011 12:12:12 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[hibernate-architecture]]></category> <category><![CDATA[Inheritance]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2454</guid> <description><![CDATA[Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Relationship Mapping in Hibernate. We saw different mapping techniques like One to Many, Many to Many using both Annotations and XML mapping. Today we will see how the Inheritance is managed in Hibernate. You may want to look at previous tutorials. Here [...]]]></description> <content:encoded><![CDATA[<p>Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Relationship Mapping in Hibernate. We saw different mapping techniques like One to Many, Many to Many using both Annotations and XML mapping.</p><p>Today we will see how the Inheritance is managed in Hibernate.</p><p>You may want to look at previous tutorials. Here is the complete list for you.</p><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div><p><br/></p><h2>Introduction to Inheritance in Hibernate</h2><p>Java is an object oriented language. It is possible to implement Inheritance in Java. Inheritance is one of the most visible facets of Object-relational mismatch. Object oriented systems can model both <strong>&#8220;is a&#8221;</strong> and <strong>&#8220;has a&#8221;</strong> relationship. Relational model supports only &#8220;has a&#8221; relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs.</p><h2>One Table Per Class Hierarchy example</h2><p>Suppose we have a class Person with subclass Employee. The properties of each class are:</p><pre>
* class Person
	- firstname
	- lastname

* class Employee
	- joining_date
	- department_name
</pre><p>In One Table per Class Hierarchy scheme, we store all the class hierarchy in a single SQL table. A discriminator is a key to uniquely identify the base type of the class hierarchy.</p><p>Following are the advantages and disadvantages of One Table per Class Hierarchy scheme.</p><h4>Advantage</h4><p>This hierarchy offers the best performance even for in the deep hierarchy since single select may suffice.</p><h4>Disadvantage</h4><p>Changes to members of the hierarchy require column to be altered, added or removed from the table.</p><h2>Create Database Table to persist Class Hierarchy</h2><pre class="brush: sql; highlight: [7]; title: ; notranslate">
CREATE TABLE `person` (
	`person_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	`joining_date` DATE NULL DEFAULT NULL,
	`department_name` VARCHAR(50) NULL DEFAULT NULL,
	`discriminator` VARCHAR(20) NOT NULL,
	PRIMARY KEY (`person_id`)
)
</pre><p>The <code>PERSON</code> table will store both <code>Employee</code> and <code>Person</code> objects.</p><h2>Hibernate Inheritance: XML Mapping</h2><p>Following is the example where we map Employee and Person entity classes using XML mapping.</p><p><em>File: Person.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Person {

	private Long personId;
	private String firstname;
	private String lastname;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Employee.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

public class Employee extends Person {

	private Date joiningDate;
	private String departmentName;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Person.hbm.xml</em></p><pre class="brush: java; highlight: [13,18,19,20,21]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Person&quot; table=&quot;PERSON&quot; discriminator-value=&quot;P&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;

		&lt;discriminator column=&quot;DISCRIMINATOR&quot; type=&quot;string&quot; /&gt;

		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;

		&lt;subclass name=&quot;Employee&quot; extends=&quot;Person&quot; discriminator-value=&quot;E&quot;&gt;
				&lt;property name=&quot;departmentName&quot; column=&quot;department_name&quot; /&gt;
				&lt;property name=&quot;joiningDate&quot; type=&quot;date&quot; column=&quot;joining_date&quot; /&gt;
		&lt;/subclass&gt;
	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p><br/></p><p>Note that we have defined only one hibernate mapping (hbm) file <code>Person.hbm.xml</code>. Both <code>Person</code> and <code>Employee</code> model class are defined within one hbm file.</p><p><strong>&lt;discriminator&gt;</strong> tag is used to define the discriminator column.</p><p><strong>&lt;subclass&gt;</strong> tag is used to map the subclass Employee. Note that we have not used the usual <code>&lt;class&gt;</code> tag to map Employee as it falls below in the hierarchy tree.</p><p>The discriminator-value for <code>Person</code> is defined as <em>&#8220;P&#8221;</em> and that for <code>Employee</code> is defined <em>&#8220;E&#8221;</em>, Thus, when Hibernate will persist the data for person or employee it will accordingly populate this value.</p><h2>Hibernate Inheritance: Annotation Mapping</h2><p>Following is the example where we map Employee and Person entity classes using JPA Annotations.</p><p><em>File: Person.java</em></p><pre class="brush: java; highlight: [16,17,18,19,20,21]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name = &quot;PERSON&quot;)
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name=&quot;discriminator&quot;,
    discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue(value=&quot;P&quot;)
public class Person {

	@Id
	@GeneratedValue
	@Column(name = &quot;PERSON_ID&quot;)
	private Long personId;

	@Column(name = &quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name = &quot;LASTNAME&quot;)
	private String lastname;

	// Constructors and Getter/Setter methods,
}
</pre><p><br/></p><p>The <code>Person</code> class is the root of hierarchy. Hence we have used some annotations to make it as the root.</p><p><strong><code>@Inheritance</code></strong> &#8211; Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.</p><p><strong><code>@DiscriminatorColumn</code></strong> &#8211; Is used to define the discriminator column for the SINGLE_TABLE and JOINED inheritance mapping strategies. The strategy and the discriminator column are only specified in the root of an entity class hierarchy or sub hierarchy in which a different inheritance strategy is applied</p><p>If the <code>@DiscriminatorColumn</code> annotation is missing, and a discriminator column is required, the name of the discriminator column defaults to <code>"DTYPE"</code> and the discriminator type to <code>DiscriminatorType.STRING</code>.</p><p><strong><code>@DiscriminatorValue</code></strong> &#8211; Is used to specify the value of the discriminator column for entities of the given type. The <code>DiscriminatorValue</code> annotation can only be specified on a concrete entity class. If the DiscriminatorValue annotation is not specified and a discriminator column is used, a provider-specific function will be used to generate a value representing the entity type. If the DiscriminatorType is STRING, the discriminator value default is the entity name.</p><p>The inheritance strategy and the discriminator column are only specified in the root of an entity class hierarchy or subhierarchy in which a different inheritance strategy is applied. The discriminator value, if not defaulted, should be specified for each entity class in the hierarchy.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [12]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

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

@Entity
@Table(name=&quot;PERSON&quot;)
@DiscriminatorValue(&quot;E&quot;)
public class Employee extends Person {

	@Column(name=&quot;joining_date&quot;)
	private Date joiningDate;

	@Column(name=&quot;department_name&quot;)
	private String departmentName;

	// Constructors and Getter/Setter methods,
}
</pre><p><br/></p><p>Employee class is child of Person class. Thus while specifying the mappings, we used <code>@DiscriminatorValue</code> to specify discriminator value. In our case &#8220;E&#8221; will be persisted in discriminator column.</p><h2>Main class</h2><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Person person = new Person(&quot;Steve&quot;, &quot;Balmer&quot;);
		session.save(person);

		Employee employee = new Employee(&quot;James&quot;, &quot;Gosling&quot;, &quot;Marketing&quot;, new Date());
		session.save(employee);

		session.getTransaction().commit();
		session.close();

	}
}
</pre><p>The Main class is used to persist <code>Person</code> and <code>Employee</code> object instance. Note that both these classes are persisted in same table <code>PERSON</code>. The discriminator column is used to distinguished between the entities.</p><h4>Output</h4><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, discriminator) values (?, ?, 'P')
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, department_name, joining_date, discriminator) values (?, ?, ?, ?, 'E')
</pre><p><img src="http://img.viralpatel.net/2011/12/hibernate-inheritence-single-table-per-heirarchy.png" alt="hibernate-inheritence-single-table-per-heirarchy" title="hibernate-inheritence-single-table-per-heirarchy" width="543" height="170" class="aligncenter size-full wp-image-2455" /></p><p><br/></p><h2>Download Source Code</h2><p><em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-heirarchy_xml.zip">Hibernate-inheritance-table-per-heirarchy_xml.zip (8 KB)</a></em><br /> <em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-heirarchy_annotation.zip">Hibernate-inheritance-table-per-heirarchy_annotation.zip (8 KB)</a></em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html" title="Introduction to Hibernate framework">Introduction to Hibernate framework</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html" title="Hibernate Self Join Annotations One To Many mapping example">Hibernate Self Join Annotations One To Many mapping example</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Hibernate Self Join Many To Many Annotations mapping example</title><link>http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html#comments</comments> <pubDate>Fri, 16 Dec 2011 13:44:04 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[annotation]]></category> <category><![CDATA[hibernate-orm]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2325</guid> <description><![CDATA[Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement Self Reference One to Many relationship using Annotation mapping. In this tutorial we will modify the source code from previous tutorial and implement Self-Join Many to Many mapping using Annotation.. Self Join: Many to Many In a query, a table that [...]]]></description> <content:encoded><![CDATA[<p>Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement <a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self Reference One to Many relationship using Annotation mapping</a>. In this tutorial we will modify the source code from previous tutorial and implement Self-Join Many to Many mapping using Annotation..</p><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div><p><br/></p><blockquote><p>Self Join: Many to Many<br /> In a query, a table that is related to itself by a connecting / bridge table. For example, an employee table defining a relationship Employee-Colleague where colleague is yet another employee. The relationship is mapped by another bridge table called Employee_Colleague table.</p></blockquote><p>Let us see how to implement <b>Self Reference Many-to-Many relationship</b> in Hibernate using Annotation.</p><h2>1. Create Database</h2><p>For this example we will MySQL database. We are using Employee / Colleagues relationship as a Self-Join Many to Many mapping example.</p><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/self-join-many-to-many.png" alt="" title="self-join-many-to-many" width="368" height="121" class="aligncenter size-full wp-image-2326" /></p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `employee` (
	`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`employee_id`)
)

CREATE TABLE `employee_colleague` (
	`employee_id` BIGINT(20) NOT NULL,
	`colleague_id` BIGINT(20) NOT NULL,
	PRIMARY KEY (`employee_id`, `colleague_id`),
	CONSTRAINT `FK_EMP` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`),
	CONSTRAINT `FK_COL` FOREIGN KEY (`colleague_id`) REFERENCES `employee` (`employee_id`)
)
</pre><p>Employee table stores information about each employee.The Employee-Colleague relationship is stored in <code>EMPLOYEE_COLLEAGUE</code> table. Both <code>employee_id</code> and <code>colleague_id</code> from <code>EMPLOYEE_COLLEAGUE</code> table is mapped to <code>employee_id</code> of <code>EMPLOYEE</code> table.</p><h2>2. Project Setup</h2><p>Download the source code: <a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-self-reference-annotation.zip">Hibernate-self-reference-annotation.zip (8 KB)</a> and import the project in Eclipse. We will update the source code.</p><h2>3. Hibernate Model Class</h2><p>We will update Employee model class and add Self Referencing Many to Many relationship.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [35,38]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

	@Id
	@Column(name=&quot;EMPLOYEE_ID&quot;)
	@GeneratedValue
	private Long employeeId;

	@Column(name=&quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name=&quot;LASTNAME&quot;)
	private String lastname;

	@ManyToMany(cascade={CascadeType.ALL})
	@JoinTable(name=&quot;EMPLOYEE_COLLEAGUE&quot;,
		joinColumns={@JoinColumn(name=&quot;EMPLOYEE_ID&quot;)},
		inverseJoinColumns={@JoinColumn(name=&quot;COLLEAGUE_ID&quot;)})
	private Set&lt;Employee&gt; colleagues = new HashSet&lt;Employee&gt;();

	@ManyToMany(mappedBy=&quot;colleagues&quot;)
	private Set&lt;Employee&gt; teammates = new HashSet&lt;Employee&gt;();

	public Employee() {
	}

	public Employee(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}

	// Getter and Setter methods
}
</pre><p>Note that we have defined two attributes <code>Set&lt;Employee&gt; colleagues</code> and <code>Set&lt;Employee&gt; teammates</code>. Also the attribute <code>colleagues</code> is relationship owner here. This is because we have marked <code>colleagues</code> attribute with <code>@JoinTable</code> annotation and <code>teammates</code> attribute with <code>mappedBy="colleagues"</code>.</p><p>Also note that the relationship is defined within table <code>EMPLOYEE_COLLEAGUE</code> which we marked using <code>@JoinTable</code> annotation.</p><p><code>@ManyToMany</code> annotation is defined on both <code>colleagues</code> and <code>teammates</code> attributes.</p><h2>4. Hibernate Configuration File</h2><p>Edit Hibernate configuration file (hibernate.cfg.xml) and add mappings for Employee class. Following is the final hibernate.cfg.xml file:</p><p><em>File: hibernate.cfg.xml</em></p><pre class="brush: xml; highlight: [21]; title: ; notranslate">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;!-- Database connection settings --&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/tutorial&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;validate&lt;/property&gt;

 	&lt;mapping class=&quot;net.viralpatel.hibernate.Employee&quot;/&gt;

    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre><h2>5. Review Project Structure</h2><p>Review your project structure.<br /> <img src="http://img.viralpatel.net/2011/12/hibernate-self-join-many-to-many-project-structure.png" alt="hibernate-self-join-many-to-many-project-structure" title="hibernate-self-join-many-to-many-project-structure" width="263" height="291" class="aligncenter size-full wp-image-2369" /></p><h3>Execute example</h3><p>Execute following Main class to test Self Reference relational using Annotation. Here we create four employee objects and map few of them as colleagues of one another.</p><p><em>File: Main.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

    public static void main(String[] args) {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        Employee employee1 = new Employee(&quot;Sergey&quot;, &quot;Brin&quot;);
        Employee employee2 = new Employee(&quot;Larry&quot;, &quot;Page&quot;);
        Employee employee3 = new Employee(&quot;Marrisa&quot;, &quot;Mayer&quot;);
        Employee employee4 = new Employee(&quot;Matt&quot;, &quot;Cutts&quot;);

        employee1.getColleagues().add(employee3);
        employee1.getColleagues().add(employee4);
        employee2.getColleagues().add(employee4);
        employee3.getColleagues().add(employee4);
        employee4.getColleagues().add(employee1);
        employee4.getColleagues().add(employee3);

        session.save(employee1);
        session.save(employee2);
        session.save(employee3);
        session.save(employee4);

        session.getTransaction().commit();
        session.close();
    }
}
</pre><p><b>Output:</b></p><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME) values (?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME) values (?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME) values (?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME) values (?, ?)
Hibernate: insert into EMPLOYEE_COLLEAGUE (EMPLOYEE_ID, COLLEAGUE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_COLLEAGUE (EMPLOYEE_ID, COLLEAGUE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_COLLEAGUE (EMPLOYEE_ID, COLLEAGUE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_COLLEAGUE (EMPLOYEE_ID, COLLEAGUE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_COLLEAGUE (EMPLOYEE_ID, COLLEAGUE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_COLLEAGUE (EMPLOYEE_ID, COLLEAGUE_ID) values (?, ?)
</pre><p>Once we execute above Main class, the employee details are saved with their relationship. Query both <code>EMPLOYEE</code> and <code>EMPLOYEE_COLLEAGUE</code> tables are see the output.</p><h4>Self Join Many-To-Many table output</h4><p><img src="http://img.viralpatel.net/2011/12/self-join-many-to-many-table-output.png" alt="self-join-many-to-many-table-output" title="self-join-many-to-many-table-output" width="292" height="298" class="aligncenter size-full wp-image-2368" /><br /> <br/></p><h2>Download Source Code</h2><p><em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-self-join-many-to-many-annotation.zip">Hibernate-self-join-many-to-many-annotation.zip (8 KB)</a></em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html" title="Hibernate Self Join Annotations One To Many mapping example">Hibernate Self Join Annotations One To Many mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Hibernate Self Join Annotations One To Many mapping example</title><link>http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html#comments</comments> <pubDate>Wed, 14 Dec 2011 13:10:18 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[annotation]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2322</guid> <description><![CDATA[Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement Many to Many relationship using Annotation mapping. In this tutorial we will modify the source code from previous Many To Many XML mapping tutorial and add JPA/Annotation support to it. Self Join: One to Many In a query, a table that [...]]]></description> <content:encoded><![CDATA[<p>Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement <a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many to Many relationship using Annotation mapping</a>. In this tutorial we will modify the source code from previous Many To Many XML mapping tutorial and add JPA/Annotation support to it.</p><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div><p><br/></p><blockquote><p>Self Join: One to Many<br /> In a query, a table that is related to itself by two different fields. For example, an employee table can include the ID of a manager who is also in the same table.</p></blockquote><p>A Self-Join or Self-Reference is basically one which has some sort of Parent/Child sturcture. We will see an example where we implement Self-Join in class of same type. For example Manager / Subordinates relationship.</p><p>Let us see how to implement <b>Self Reference One-to-Many relationship</b> in Hibernate using Annotation.</p><h2>1. Create Database</h2><p>For this example, we will MySQL database. We are using Manager / Subordinates relationship as a Self-Join One to Many mapping example. Each manager is an employee. Hence we implement a Parent/Child relationship in Employee enitity.</p><p><img src="http://img.viralpatel.net/2011/12/self-join-one-to-many.png" alt="self-join-one-to-many" title="self-join-one-to-many" width="319" height="149" class="aligncenter size-full wp-image-2324" /></p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `employee` (
	`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	`manager_id` BIGINT(20) NULL DEFAULT NULL,
	PRIMARY KEY (`employee_id`),
	CONSTRAINT `FK_MANAGER` FOREIGN KEY (`manager_id`) REFERENCES `employee` (`employee_id`)
)
</pre><p>Here in Employee table, we defined a column MANAGER_ID which is mapped to the same table&#8217;s primary key. Thus for each employee we will store its manager&#8217;s id also. Manager will be yet another employee in this table.</p><h2>2. Project Setup</h2><p>Download the source code: <a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-many-to-many-annotation.zip">Hibernate-many-to-many-annotation.zip (8 KB)</a> and import the project in Eclipse. We will update the source code.</p><h2>3. Update Hibernate Model Class</h2><p>We will update Employee and Meeting model classes and add Annotations to map them with database table.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [31,32,33,35,36]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

	@Id
	@Column(name=&quot;EMPLOYEE_ID&quot;)
	@GeneratedValue
	private Long employeeId;

	@Column(name=&quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name=&quot;LASTNAME&quot;)
	private String lastname;

	@ManyToOne(cascade={CascadeType.ALL})
	@JoinColumn(name=&quot;manager_id&quot;)
	private Employee manager;

	@OneToMany(mappedBy=&quot;manager&quot;)
	private Set&lt;Employee&gt; subordinates = new HashSet&lt;Employee&gt;();

	public Employee() {
	}

	public Employee(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}

	// Getter and Setter methods
}
</pre><p>Note that in Employee entity class, we defined two new attributes: <code>Employee manager</code> and <code>Set&lt;Employee&gt; subordinates</code>. Attribute <code>manager</code> is mapped with <code>@ManyToOne</code> annotation and <code>subordinates</code> is mapped with <code>@OneToMany</code>. Also within <code>@OneToMany</code> attribute we defined <code>mappedBy="manager"</code> making manager as the relationship owner and thus which manages the foreign relationship within table.</p><p>Also the annotation <code>@JoinColumn</code> is defined on manager making it the relationship owner. @JoinColumn defines the joining column which in our case is <code>manager_id</code>.</p><h2>4. Hibernate Configuration File</h2><p>Edit Hibernate configuration file (hibernate.cfg.xml) and add mappings for Employee and Meeting classes. Following is the final hibernate.cfg.xml file:</p><p><em>File: hibernate.cfg.xml</em></p><pre class="brush: xml; highlight: [21]; title: ; notranslate">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;!-- Database connection settings --&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/tutorial&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;validate&lt;/property&gt;

 	&lt;mapping class=&quot;net.viralpatel.hibernate.Employee&quot;/&gt;

    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre><h2>5. Review Project Structure</h2><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/hibernate-self-join-one-to-many-project-structure.png" alt="hibernate-self-join-one-to-many-project-structure" title="hibernate-self-join-one-to-many-project-structure" width="264" height="292" class="aligncenter size-full wp-image-2332" /></p><h3>Execute example</h3><p>Execute following Main class to test Self Reference relational using Annotation.</p><p><em>File: Main.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

    public static void main(String[] args) {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        Employee manager1 = new Employee(&quot;Chuck&quot;, &quot;Norris&quot;);

        Employee employee1 = new Employee(&quot;Sergey&quot;, &quot;Brin&quot;);
        Employee employee2 = new Employee(&quot;Larry&quot;, &quot;Page&quot;);

        employee1.setManager(manager1);
        employee2.setManager(manager1);

        session.save(employee1);
        session.save(employee2);

        session.getTransaction().commit();
        session.close();
    }
}
</pre><p>We created one manager &#8220;Chuck Norris&#8221; and two employees &#8220;Sergey Brin&#8221; and &#8220;Larry Page&#8221;. We set the manager details for each employees and saved the employee. Following are the sql statements generated by Hibernate.</p><p><b>Output:</b></p><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, manager_id) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, manager_id) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, manager_id) values (?, ?, ?)
</pre><h4>Self Join EMPLOYEE table</h4><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/self-join-table-output-employee-manager.png" alt="self-join-table-output-employee-manager" title="self-join-table-output-employee-manager" width="357" height="101" class="aligncenter size-full wp-image-2331" /></p><h2>Download Source Code</h2><p><em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-self-reference-annotation.zip">Hibernate-self-reference-annotation.zip (8 KB)</a></em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html" title="Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)">Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Hibernate Many To Many Annotation Mapping Tutorial</title><link>http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html#comments</comments> <pubDate>Tue, 13 Dec 2011 12:45:10 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[annotation]]></category> <category><![CDATA[maven]]></category> <category><![CDATA[MySQL]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2317</guid> <description><![CDATA[Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement Many to Many relationship using XML mapping. In this tutorial we will modify the source code from previous Many To Many XML mapping tutorial and add JPA/Annotation support to it. Let us see how to implement Many-to-Many relationship in Hibernate using [...]]]></description> <content:encoded><![CDATA[<p>Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement <a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many to Many relationship using XML mapping</a>. In this tutorial we will modify the source code from previous Many To Many XML mapping tutorial and add JPA/Annotation support to it.</p><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div><p><br/></p><p>Let us see how to implement <b>Many-to-Many relationship</b> in Hibernate using Annotation.</p><h2>1. Create Database</h2><p>For this example, we will MySQL database. We are using Employee-Meeting relationship as a many to many relationship example. Each Employee can attain more than one meetings and each meetings can have more than one employee<br /> .<br /> <img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/many-to-many-relationship-diagram.png" alt="many-to-many-relationship-diagram" title="many-to-many-relationship-diagram" width="466" height="139" class="aligncenter size-full wp-image-2304" /></p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `employee` (
	`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`employee_id`)
)

CREATE TABLE `meeting` (
	`meeting_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`subject` VARCHAR(50) NOT NULL,
	`meeting_date` DATE NOT NULL,
	PRIMARY KEY (`meeting_id`)
)

CREATE TABLE `employee_meeting` (
	`employee_id` BIGINT(20) NOT NULL,
	`meeting_id` BIGINT(20) NOT NULL,
	PRIMARY KEY (`employee_id`, `meeting_id`),
	INDEX `FK_MEETING` (`meeting_id`),
	CONSTRAINT `FK_EMPLOYEE` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`),
	CONSTRAINT `FK_MEETING` FOREIGN KEY (`meeting_id`) REFERENCES `meeting` (`meeting_id`)
)
</pre><h2>2. Project Setup</h2><p>Download the source code: <a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-many-to-many-set-xml.zip">Hibernate-many-to-many-set-xml.zip (9 KB)</a> and import the project in Eclipse. We will update the source code.</p><h2>3. Update Maven Dependency</h2><p><em>File: pom.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;project&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;HibernateCache&lt;/groupId&gt;
  &lt;artifactId&gt;HibernateCache&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;description&gt;&lt;/description&gt;
  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;ejb3-persistence&lt;/artifactId&gt;
      &lt;version&gt;1.0.1.GA&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;
      &lt;version&gt;3.3.1.GA&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;mysql&lt;/groupId&gt;
      &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
      &lt;version&gt;5.1.10&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/project&gt;
</pre><h2>3. Remove Hibernate Mapping (hbm) Files</h2><p>We are not going to use hibernate mapping files or hbm files as we will map the model using Java 5 Annotations. Delete the files <code>employee.hbm.xml</code> and <code>meeting.hbm.xml</code>.</p><h2>4. Update Hibernate Model Class</h2><p>We will update Employee and Meeting model classes and add Annotations to map them with database table.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [31,32,33,34]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

	@Id
	@Column(name=&quot;EMPLOYEE_ID&quot;)
	@GeneratedValue
	private Long employeeId;

	@Column(name=&quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name=&quot;LASTNAME&quot;)
	private String lastname;

	@ManyToMany(cascade = {CascadeType.ALL})
	@JoinTable(name=&quot;EMPLOYEE_MEETING&quot;,
				joinColumns={@JoinColumn(name=&quot;EMPLOYEE_ID&quot;)},
				inverseJoinColumns={@JoinColumn(name=&quot;MEETING_ID&quot;)})
	private Set&lt;Meeting&gt; meetings = new HashSet&lt;Meeting&gt;();

	public Employee() {
	}

	public Employee(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}

	// Getter and Setter methods
}
</pre><p><em>File: Meeting.java</em></p><pre class="brush: java; highlight: [29]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

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

@Entity
@Table(name=&quot;MEETING&quot;)
public class Meeting {

	@Id
	@Column(name=&quot;MEETING_ID&quot;)
	@GeneratedValue
	private Long meetingId;

	@Column(name=&quot;SUBJECT&quot;)
	private String subject;

	@Column(name=&quot;MEETING_DATE&quot;)
	private Date meetingDate;

	@ManyToMany(mappedBy=&quot;meetings&quot;)
	private Set&lt;Employee&gt; employees = new HashSet&lt;Employee&gt;();

	public Meeting(String subject) {
		this.subject = subject;
		this.meetingDate = new Date();
	}

	// Getter and Setter methods
}
</pre><p>Let us understand the annotations we used here to map Many to many relationship.</p><p><b><code>@ManyToMany</code></b> &#8211; Is used to create many-to-many relationship between <code>Employee</code> and <code>Meeting</code> entities. If the Collection is defined using generics to specify the element type, the associated target entity class does not need to be specified; otherwise it must be specified. Every many-to-many association has two sides, the owning side and the non-owning, or inverse, side. The join table is specified on the owning side. If the association is bidirectional, either side may be designated as the owning side.</p><p>Note that in above entity classes, Employee is defined as relationship owner as <code>@JoinColumn</code> is define in <code>Employee</code> class and <code>mappedBy</code> is specified in Meeting class.</p><p><b><code>@JoinTable</code></b> &#8211; Is used to define the join table (link table) for many-to-many relationship. It is specified on the owning side of a many-to-many association, or in a unidirectional one-to-many association. In this case the join table is <code>EMPLOYEE_MEETING</code>.</p><p>If the JoinTable annotation is missing, the default values of the annotation elements apply. The name of the join table is assumed to be the table names of the associated primary tables concatenated together (owning side first) using an underscore.</p><p><b><code>@JoinColumn</code></b> &#8211; Is used to define the join column (linking column) in both main tables.</p><p>Note that we have used SET to map meetings with employee and vice versa. A &lt;set&gt; is similar to <bag> except that it can only store unique objects. That means no duplicate elements can be contained in a set. When you add the same element to a set for second time, it will replace the old one. A set is unordered by default but we can ask it to be sorted. The corresponding type of a &lt;set&gt; in Java is <code>java.util.Set</code>.</p><h2>5. Hibernate Utility Class</h2><p>In previous example, the Hibernate Utility class uses Hibernate&#8217;s <code>org.hibernate.cfg.Configuration</code> class to generate SessionFactory. For this example we will replace this class with <code>org.hibernate.cfg.AnnotationConfiguration</code> class. Following is the code for <code>HibernateUtil.java</code> class.</p><p><em>File: HibernateUtil.java</em></p><pre class="brush: java; highlight: [13,14]; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure()
                    .buildSessionFactory();

        } catch (Throwable ex) {
            System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
</pre><h2>6. Hibernate Configuration File</h2><p>Edit Hibernate configuration file (hibernate.cfg.xml) and add mappings for Employee and Meeting classes. Following is the final hibernate.cfg.xml file:</p><p><em>File: hibernate.cfg.xml</em></p><pre class="brush: xml; highlight: [21,22]; title: ; notranslate">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;!-- Database connection settings --&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/tutorial&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;validate&lt;/property&gt;

 	&lt;mapping class=&quot;net.viralpatel.hibernate.Employee&quot;/&gt;
 	&lt;mapping class=&quot;net.viralpatel.hibernate.Meeting&quot;/&gt;

    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre><h2>7. Review Project Structure</h2><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/many-to-many-annotation-project-structure.png" alt="many-to-many-annotation-project-structure" title="many-to-many-annotation-project-structure" width="260" height="306" class="aligncenter size-full wp-image-2318" /></p><h3>Execute example</h3><p>Execute following Main class to test Many-to-many relational mapping using Annotation.</p><p><em>File: Main.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

    public static void main(String[] args) {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        Meeting meeting1 = new Meeting(&quot;Quaterly Sales meeting&quot;);
        Meeting meeting2 = new Meeting(&quot;Weekly Status meeting&quot;);

        Employee employee1 = new Employee(&quot;Sergey&quot;, &quot;Brin&quot;);
        Employee employee2 = new Employee(&quot;Larry&quot;, &quot;Page&quot;);

        employee1.getMeetings().add(meeting1);
        employee1.getMeetings().add(meeting2);
        employee2.getMeetings().add(meeting1);

        session.save(employee1);
        session.save(employee2);

        session.getTransaction().commit();
        session.close();
    }
}
</pre><p><b>Output:</b></p><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into EMPLOYEE (firstname, lastname) values (?, ?)
Hibernate: insert into MEETING (SUBJECT, MEETING_DATE) values (?, ?)
Hibernate: insert into MEETING (SUBJECT, MEETING_DATE) values (?, ?)
Hibernate: insert into EMPLOYEE (firstname, lastname) values (?, ?)
Hibernate: insert into EMPLOYEE_MEETING (EMPLOYEE_ID, MEETING_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_MEETING (EMPLOYEE_ID, MEETING_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_MEETING (EMPLOYEE_ID, MEETING_ID) values (?, ?)
</pre><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/many-to-many-hibernate-output-table.png" alt="many-to-many-hibernate-output-table" title="many-to-many-hibernate-output-table" width="364" height="262" class="aligncenter size-full wp-image-2307" /></p><h2>Download Source Code</h2><p><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-many-to-many-annotation.zip"><em>Hibernate-many-to-many-annotation.zip (8 KB)</em></a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Hibernate Many To Many XML Mapping Tutorial</title><link>http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html#comments</comments> <pubDate>Fri, 09 Dec 2011 13:57:26 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[maven]]></category> <category><![CDATA[MySQL]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2291</guid> <description><![CDATA[Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement One to Many Annotation mapping as well as XML mapping. In this tutorial we will understand How to implement Bi-directional Many-to-Many relationship in Hibernate using XML mappings. First let us see the formal definition of Many-to-Many relationship: Many-To-Many Relationship: A logical [...]]]></description> <content:encoded><![CDATA[<p>Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement <a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One to Many Annotation mapping</a> as well as <a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">XML mapping</a>. In this tutorial we will understand How to implement Bi-directional Many-to-Many relationship in Hibernate using XML mappings.<br /><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div></p><p>First let us see the formal definition of Many-to-Many relationship:</p><blockquote><p>Many-To-Many Relationship:<br /> A logical data relationship in which the value of one data element can exist in combination with many values of another data element, and vice versa.</p></blockquote><p>Let us see how to implement <b>Many-to-Many relationship</b> in Hibernate using XML mapping.</p><h2>1. Create Database</h2><p>For this example, we will MySQL database. We are using Employee-Meeting relationship as a many to many relationship example. Each Employee can attain more than one meetings and each meetings can have more than one employee<br /> .<br /> <img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/many-to-many-relationship-diagram.png" alt="many-to-many-relationship-diagram" title="many-to-many-relationship-diagram" width="466" height="139" class="aligncenter size-full wp-image-2304" /></p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `employee` (
	`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`employee_id`)
)

CREATE TABLE `meeting` (
	`meeting_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`subject` VARCHAR(50) NOT NULL,
	`meeting_date` DATE NOT NULL,
	PRIMARY KEY (`meeting_id`)
)

CREATE TABLE `employee_meeting` (
	`employee_id` BIGINT(20) NOT NULL,
	`meeting_id` BIGINT(20) NOT NULL,
	PRIMARY KEY (`employee_id`, `meeting_id`),
	INDEX `FK_MEETING` (`meeting_id`),
	CONSTRAINT `FK_EMPLOYEE` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`),
	CONSTRAINT `FK_MEETING` FOREIGN KEY (`meeting_id`) REFERENCES `meeting` (`meeting_id`)
)
</pre><h2>2. Hibernate Maven Dependency</h2><p>We are using Maven for dependency management. Copy following in the pom.xml.</p><p><em>File: pom.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;groupId&gt;net.viralpatel.hibernate&lt;/groupId&gt;
	&lt;artifactId&gt;HibernateHelloWorldXML&lt;/artifactId&gt;
	&lt;packaging&gt;jar&lt;/packaging&gt;
	&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
	&lt;name&gt;HibernateHelloWorldXML&lt;/name&gt;
	&lt;url&gt;http://maven.apache.org&lt;/url&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;mysql&lt;/groupId&gt;
			&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
			&lt;version&gt;5.1.10&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
			&lt;artifactId&gt;hibernate&lt;/artifactId&gt;
			&lt;version&gt;3.2.6.ga&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
&lt;/project&gt;
</pre><h2>3. Hibernate Model Class</h2><p>Employee and Department model classes are created which maps to the corresponding database tables.</p><p><em>File: Employee.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.HashSet;
import java.util.Set;

public class Employee {

	private Long employeeId;
	private String firstname;
	private String lastname;

	private Set&lt;Meeting&gt; meetings = new HashSet&lt;Meeting&gt;();

	public Employee() {
	}

	public Employee(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}

	// Getter and Setter methods
}
</pre><p><em>File: Meeting.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class Meeting {

	private Long meetingId;
	private String subject;
	private Date meetingDate;

	private Set&lt;Employee&gt; employees = new HashSet&lt;Employee&gt;();

	public Meeting(String subject) {
		this.subject = subject;
		this.meetingDate = new Date();
	}

	// Getter and Setter methods
}
</pre><h2>4. Hibernate Utility Class</h2><p>To access Hibernate API, we will create a wrapper utility class which provides us with SessionFactory.</p><p><em>File: HibernateUtil.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

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

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}
</pre><h2>5. Hibernate Mapping XML (hbm)</h2><p>Following are the hibernate mapping files for each enitity Employee and Department.</p><p><em>File: Employee.hbm.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Employee&quot; table=&quot;EMPLOYEE&quot;&gt;
		&lt;id name=&quot;employeeId&quot; column=&quot;EMPLOYEE_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;

		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;

		&lt;set name=&quot;meetings&quot; table=&quot;EMPLOYEE_MEETING&quot;
			inverse=&quot;false&quot; lazy=&quot;true&quot; fetch=&quot;select&quot; cascade=&quot;all&quot;&gt;
			&lt;key column=&quot;EMPLOYEE_ID&quot; /&gt;
			&lt;many-to-many column=&quot;MEETING_ID&quot; class=&quot;Meeting&quot; /&gt;
		&lt;/set&gt;

	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p><em>File: Meeting.hbm.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Meeting&quot; table=&quot;MEETING&quot;&gt;

		&lt;id name=&quot;meetingId&quot; type=&quot;java.lang.Long&quot;
			column=&quot;MEETING_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;

		&lt;property name=&quot;subject&quot; column=&quot;SUBJECT&quot; /&gt;
		&lt;property name=&quot;meetingDate&quot; type=&quot;date&quot; column=&quot;MEETING_DATE&quot; /&gt;

		&lt;set name=&quot;employees&quot; table=&quot;EMPLOYEE_MEETING&quot;
			inverse=&quot;true&quot; lazy=&quot;true&quot; fetch=&quot;select&quot;&gt;
			&lt;key column=&quot;EMPLOYEE_ID&quot; /&gt;
			&lt;many-to-many column=&quot;MEETING_ID&quot; class=&quot;Meeting&quot; /&gt;
		&lt;/set&gt;

	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p>One thing is worth noting here is that we have mentioned keyword <b>inverse=&#8221;true&#8221;</b> in <code>Meeting</code> class which makes <code>Employee</code> as relationship owner. Thus Employee model takes care of updating referential keys in dependent models.</p><h2>6. Hibernate Configuration File</h2><p>Add following hibernate.cfg.xml file in your project.</p><p><em>File: hibernate.cfg.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/tutorial&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;validate&lt;/property&gt;

        &lt;mapping resource=&quot;net/viralpatel/hibernate/Employee.hbm.xml&quot;/&gt;
        &lt;mapping resource=&quot;net/viralpatel/hibernate/Meeting.hbm.xml&quot;/&gt;

    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre><h2>7. Review Project Structure</h2><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/hibernate-many-to-many-example-project-structure.png" alt="hibernate-many-to-many-example-project-structure" title="hibernate-many-to-many-example-project-structure" width="270" height="343" class="aligncenter size-full wp-image-2306" /></p><p>Note that we have used SET to map meetings with employee and vice versa. A &lt;set&gt; is similar to <bag> except that it can only store unique objects. That means no duplicate elements can be contained in a set. When you add the same element to a set for second time, it will replace the old one. A set is unordered by default but we can ask it to be sorted. The corresponding type of a &lt;set&gt; in Java is <code>java.util.Set</code>.</p><h3>Execute example</h3><p><em>File: Main.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

    public static void main(String[] args) {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        Meeting meeting1 = new Meeting(&quot;Quaterly Sales meeting&quot;);
        Meeting meeting2 = new Meeting(&quot;Weekly Status meeting&quot;);

        Employee employee1 = new Employee(&quot;Sergey&quot;, &quot;Brin&quot;);
        Employee employee2 = new Employee(&quot;Larry&quot;, &quot;Page&quot;);

        employee1.getMeetings().add(meeting1);
        employee1.getMeetings().add(meeting2);
        employee2.getMeetings().add(meeting1);

        session.save(employee1);
        session.save(employee2);

        session.getTransaction().commit();
        session.close();
    }
}
</pre><p><b>Output:</b></p><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into EMPLOYEE (firstname, lastname) values (?, ?)
Hibernate: insert into MEETING (SUBJECT, MEETING_DATE) values (?, ?)
Hibernate: insert into MEETING (SUBJECT, MEETING_DATE) values (?, ?)
Hibernate: insert into EMPLOYEE (firstname, lastname) values (?, ?)
Hibernate: insert into EMPLOYEE_MEETING (EMPLOYEE_ID, MEETING_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_MEETING (EMPLOYEE_ID, MEETING_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_MEETING (EMPLOYEE_ID, MEETING_ID) values (?, ?)
</pre><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/many-to-many-hibernate-output-table.png" alt="many-to-many-hibernate-output-table" title="many-to-many-hibernate-output-table" width="364" height="262" class="aligncenter size-full wp-image-2307" /></p><h2>Download Source Code</h2><p><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-many-to-many-set-xml.zip">Hibernate-many-to-many-set-xml.zip (9 KB)</a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Hibernate One To Many Annotation tutorial</title><link>http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html#comments</comments> <pubDate>Thu, 08 Dec 2011 10:59:44 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[annotation]]></category> <category><![CDATA[hibernate-architecture]]></category> <category><![CDATA[hibernate-orm]]></category> <category><![CDATA[maven]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2270</guid> <description><![CDATA[Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement One to Many relationship using XML mapping. In this tutorial we will modify the source code from previous One To Many XML mapping tutorial and add JPA/Annotation support to it. 1. Database Setup For this example, we will use MySQL database. [...]]]></description> <content:encoded><![CDATA[<p>Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement <a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One to Many relationship using XML mapping</a>. In this tutorial we will modify the source code from previous One To Many XML mapping tutorial and add JPA/Annotation support to it.<br /><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div></p><h2>1. Database Setup</h2><p>For this example, we will use MySQL database. Create following two tables in MySQL. Note that Employee and Department table exhibits One-to-many relationship. Each Department can be associated with multiple Employees and each Employee can have only one Department.<br /> <img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/one-to-many-relationship-diagram.png" alt="one-to-many-relationship-diagram" title="one-to-many-relationship-diagram" width="384" height="164" class="aligncenter size-full wp-image-2257" /></p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `department` (
	`department_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`dept_name` VARCHAR(50) NOT NULL DEFAULT '0',
	PRIMARY KEY (`department_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=115

CREATE TABLE `employee` (
	`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	`birth_date` DATE NULL DEFAULT NULL,
	`cell_phone` VARCHAR(15) NULL DEFAULT NULL,
	`department_id` BIGINT(20) NULL DEFAULT NULL,
	PRIMARY KEY (`employee_id`),
	INDEX `FK_DEPT` (`department_id`),
	CONSTRAINT `FK_DEPT` FOREIGN KEY (`department_id`) REFERENCES `department` (`department_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
</pre><h2>2. Project Setup</h2><p>Download the source code: <a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-one-to-many-set-xml.zip">Hibernate-one-to-many-set-example.zip (9 KB)</a> and import the project in Eclipse. We will update the source code.</p><h2>3. Update Maven Dependency</h2><p><em>File: pom.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;project&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;HibernateCache&lt;/groupId&gt;
  &lt;artifactId&gt;HibernateCache&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;description&gt;&lt;/description&gt;
  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;ejb3-persistence&lt;/artifactId&gt;
      &lt;version&gt;1.0.1.GA&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;
      &lt;version&gt;3.3.1.GA&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;mysql&lt;/groupId&gt;
      &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
      &lt;version&gt;5.1.10&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/project&gt;
</pre><h2>3. Remove Hibernate Mapping (hbm) Files</h2><p>We are not going to use hibernate mapping files or hbm files as we will map the model using Java 5 Annotations. Delete the files <code>employee.hbm.xml</code> and <code>department.hbm.xml</code>.</p><h2>4. Update Hibernate Model Class</h2><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [35,36]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

	@Id
	@GeneratedValue
	@Column(name=&quot;employee_id&quot;)
	private Long employeeId;

	@Column(name=&quot;firstname&quot;)
	private String firstname;

	@Column(name=&quot;lastname&quot;)
	private String lastname;

	@Column(name=&quot;birth_date&quot;)
	private Date birthDate;

	@Column(name=&quot;cell_phone&quot;)
	private String cellphone;

	@ManyToOne
	@JoinColumn(name=&quot;department_id&quot;)
	private Department department;

	public Employee() {

	}

	public Employee(String firstname, String lastname, String phone) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.birthDate = new Date(System.currentTimeMillis());
		this.cellphone = phone;
	}

	// Getter and Setter methods
}
</pre><p><code>@ManyToOne</code> annotation defines a single-valued association to another entity class that has many-to-one multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced.</p><p><code>@JoinColumn</code> is used to specify a mapped column for joining an entity association.</p><p><em>File: Department.java</em></p><pre class="brush: java; highlight: [24]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Set;

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

@Entity
@Table(name=&quot;DEPARTMENT&quot;)
public class Department {

	@Id
	@GeneratedValue
	@Column(name=&quot;DEPARTMENT_ID&quot;)
	private Long departmentId;

	@Column(name=&quot;DEPT_NAME&quot;)
	private String departmentName;

	@OneToMany(mappedBy=&quot;department&quot;)
	private Set&lt;Employee&gt; employees;

	// Getter and Setter methods
}
</pre><p><code>@OneToMany</code> annotation defines a many-valued association with one-to-many multiplicity.<br /> If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified.</p><p>The association may be bidirectional. In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute <code>mappedBy</code> is used. <code>mappedBy</code> refers to the property name of the association on the owner side. In our case, this is passport. As you can see, you don&#8217;t have to (must not) declare the join column since it has already been declared on the owners side.</p><h2>5. Update Hibernate Configuration File</h2><p><em>File: hibernate.cfg.xml</em></p><pre class="brush: xml; highlight: [21,22]; title: ; notranslate">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;!-- Database connection settings --&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/tutorial&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;validate&lt;/property&gt;

	&lt;mapping class=&quot;net.viralpatel.hibernate.Department&quot;/&gt;
	&lt;mapping class=&quot;net.viralpatel.hibernate.Employee&quot;/&gt;

    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre><h2>6. Review Project Structure</h2><p>Once all the source files are in place, the project structure should looks like below:</p><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/hibernate-one-to-many-annotation-project-structure.png" alt="" title="hibernate-one-to-many-annotation-project-structure" width="264" height="308" class="aligncenter size-full wp-image-2275" /></p><h2>7. Execute example</h2><p>Execute following Main.java file which will create one Department and two Employees.<br /> <em>File: Main.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	@SuppressWarnings(&quot;unchecked&quot;)
	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Department department = new Department();
		department.setDepartmentName(&quot;Sales&quot;);
		session.save(department);

		Employee emp1 = new Employee(&quot;Nina&quot;, &quot;Mayers&quot;, &quot;111&quot;);
		Employee emp2 = new Employee(&quot;Tony&quot;, &quot;Almeida&quot;, &quot;222&quot;);

		emp1.setDepartment(department);
		emp2.setDepartment(department);

		session.save(emp1);
		session.save(emp2);

		session.getTransaction().commit();
		session.close();
	}
}
</pre><p><b>Output:</b></p><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into DEPARTMENT (DEPT_NAME) values (?)
Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)
Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)
</pre><p>Thus we saw in above example how to implement One to Many relationship in Hibernate using Annotation. Also we used <code>java.util.Set</code> for our example.</p><h2>8. One- To Many Bi-directional Indexed mapping</h2><p>Above example was pretty straightforward. We mapped multiple employees with a department. For this we used <code>java.lang.Set</code>. But the order in which the employees are mapped with department is not conserved. What if you have a requirement where you want to preserve order for entities that you save.</p><p>We can use <code>java.util.List</code> to map ordered entities. For this first we will need to add a column <code>IDX</code> in <code>Employee</code> table which will store the index value.</p><h4>8.1 Modify Employee table</h4><pre class="brush: sql; highlight: [8]; title: ; notranslate">
CREATE TABLE `employee` (
	`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	`birth_date` DATE NULL DEFAULT NULL,
	`cell_phone` VARCHAR(15) NULL DEFAULT NULL,
	`department_id` BIGINT(20) NULL DEFAULT NULL,
	`idx` INT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`employee_id`),
	INDEX `FK_DEPT` (`department_id`),
	CONSTRAINT `FK_DEPT` FOREIGN KEY (`department_id`) REFERENCES `department` (`department_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=33
</pre><h4>8.2 Modify Hibernate Model classes</h4><p>Update Employee.java and Department.java model classes and add the list support. Also note that we are changing the annotations.</p><p><em>File: Department.java</em></p><pre class="brush: java; highlight: [28,29,30]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.IndexColumn;

@Entity
@Table(name=&quot;DEPARTMENT&quot;)
public class Department {

	@Id
	@GeneratedValue
	@Column(name=&quot;DEPARTMENT_ID&quot;)
	private Long departmentId;

	@Column(name=&quot;DEPT_NAME&quot;)
	private String departmentName;

	@OneToMany(cascade={CascadeType.ALL})
	@JoinColumn(name=&quot;department_id&quot;)
	@IndexColumn(name=&quot;idx&quot;)
	private List&lt;Employee&gt; employees;

	// Getter and Setter methods
}
</pre><p>Note that in Department entity class, we removed <b>mappedBy</b> clause from <code>@OneToMany</code>. This mark Department as the relationship owner and make it responsible to update foriegn keys and index values.</p><p>Also we specified index coulmn using <code>@IndexColumn</code> annotation to specify which column in Employee table we would like to store index in.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [34,35,36,37]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

	@Id
	@GeneratedValue
	@Column(name=&quot;employee_id&quot;)
	private Long employeeId;

	@Column(name=&quot;firstname&quot;)
	private String firstname;

	@Column(name=&quot;lastname&quot;)
	private String lastname;

	@Column(name=&quot;birth_date&quot;)
	private Date birthDate;

	@Column(name=&quot;cell_phone&quot;)
	private String cellphone;

	@ManyToOne
	@JoinColumn(name=&quot;department_id&quot;,
				insertable=false, updatable=false,
				nullable=false)
	private Department department;

	public Employee() {

	}

	public Employee(String firstname, String lastname, String phone) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.birthDate = new Date(System.currentTimeMillis());
		this.cellphone = phone;
	}

	// Getter and Setter methods
}
</pre><h4>8.3 Execute List example</h4><p><em>File: Department.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.ArrayList;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	@SuppressWarnings(&quot;unchecked&quot;)
	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Department department = new Department();
		department.setDepartmentName(&quot;Sales&quot;);

		Employee emp1 = new Employee(&quot;Nina&quot;, &quot;Mayers&quot;, &quot;111&quot;);
		Employee emp2 = new Employee(&quot;Tony&quot;, &quot;Almeida&quot;, &quot;222&quot;);

		department.setEmployees(new ArrayList&lt;Employee&gt;());
		department.getEmployees().add(emp1);
		department.getEmployees().add(emp2);

		session.save(department);

		session.getTransaction().commit();
		session.close();
	}
}
</pre><p><b>Output:</b></p><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into DEPARTMENT (DEPT_NAME) values (?)
Hibernate: insert into EMPLOYEE (birth_date, cell_phone, firstname, lastname) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE (birth_date, cell_phone, firstname, lastname) values (?, ?, ?, ?)
Hibernate: update EMPLOYEE set department_id=?, idx=? where employee_id=?
Hibernate: update EMPLOYEE set department_id=?, idx=? where employee_id=?
</pre><p><br/></p><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/12/one-to-many-list-result.png" alt="one-to-many-list-result" title="one-to-many-list-result" width="621" height="168" class="aligncenter size-full wp-image-2261" /></p><p><br/></p><h2>Download Source Code</h2><p><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-One-To-Many-Annotation-Set.zip">Hibernate-One-To-Many-Annotation-Set.zip (8 KB)</a><br /> <a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-One-To-Many-Annotation-List.zip">Hibernate-One-To-Many-Annotation-List.zip (8 KB)</a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html" title="Introduction to Hibernate framework">Introduction to Hibernate framework</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-02-04 11:34:27 -->
