<?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>JavaBeat &#187; Database</title>
	<atom:link href="http://www.javabeat.net/category/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Mon, 13 May 2013 20:10:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Hibernate Many-To-Many Mapping Example Using Annotations</title>
		<link>http://www.javabeat.net/2013/03/hibernate-many-to-many-example-annotations/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-many-to-many-example-annotations/#comments</comments>
		<pubDate>Fri, 22 Mar 2013 12:21:33 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6327</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate Many to Many Mapping using Java Annotations. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate Many to Many Mapping</strong></span> using <strong>Java Annotations</strong>. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a></p>
<h2>Many To Many Relationship</h2>
<p>A ManyToMany relationship in Java is where the source object has an attribute that stores a collection of target objects and (if) those target objects had the inverse relationship back to the source object it would also be a ManyToMany relationship.</p>
<p>All ManyToMany relationships require a <b>JoinTable</b>. The JoinTable is defined using the <b>@JoinTable</b> annotation and <b></b> XML element. The JoinTable defines a foreign key to the source object&#8217;s primary key (joinColumns), and a foreign key to the target object&#8217;s primary key (inverseJoinColumns). Normally the primary key of the JoinTable is the combination of both foreign keys. Let&#8217;s see an example of person and phone relationship as in the below structure:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_tablestruct.jpg"><img class="size-medium wp-image-6331 aligncenter" alt="manytomany_tablestruct" src="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_tablestruct-300x60.jpg" width="300" height="60" /></a></p>
<p>Each person can have more than one phone and each phone can have more than one person assoiated with it.</p>
<p><span style="text-decoration: underline;"><strong>Technologies Used:</strong></span><strong></strong></p>
<p>Following are the tools and technologies required for this project:</p>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (<a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">Hibernate Downloads</a>)</li>
<li>MySQL 5 above (<a href="http://dev.mysql.com/downloads/connector/j/5.1.html" target="_blank">MySql Downloads</a>)</li>
</ol>
<h2>1.Environment Setup</h2>
<p>Refer post <a title="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping)</a> for environment setup (follow steps 1,2 and 3). Pass the following command in the step.1, to create a java project using Maven:</p>
<pre class="brush: java; title: ; notranslate">
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateManyToManyAnnotations
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
</pre>
<h2>2. Adding dependencies to pom.xml</h2>
<p>We need to add the Hibernate, <strong>MYSQL</strong> and some other dependencies to the Maven pom.xml as shown below:</p>
<pre class="brush: java; title: ; notranslate">
 &amp;lt;project xmlns=&amp;quot;http://maven.apache.org/POM/4.0.0&amp;quot; xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;
   xsi:schemaLocation=&amp;quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&amp;quot;&amp;gt;
   &amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;
   &amp;lt;groupId&amp;gt;net.javabeat.hibernate&amp;lt;/groupId&amp;gt;
   &amp;lt;artifactId&amp;gt; HibernateManyToManyAnnotations&amp;lt;/artifactId&amp;gt;
   &amp;lt;packaging&amp;gt;jar&amp;lt;/packaging&amp;gt;
   &amp;lt;version&amp;gt;1.0-SNAPSHOT&amp;lt;/version&amp;gt;
   &amp;lt;name&amp;gt; HibernateManyToManyAnnotations&amp;lt;/name&amp;gt;
   &amp;lt;url&amp;gt;http://maven.apache.org&amp;lt;/url&amp;gt;
   &amp;lt;dependencies&amp;gt;
     &amp;lt;!-- Hibernate library dependency start --&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;org.hibernate&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;hibernate&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;4.1.9.Final&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;

 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;mysql&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;mysql-connector-java&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;5.1.10&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;org.hibernate&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;hibernate-annotations&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;3.3.1.GA&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;dom4j&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;dom4j&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;1.6.1&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;commons-logging&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;commons-logging&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;1.1.1&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;commons-collections&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;commons-collections&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;3.2.1&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;cglib&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;cglib&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;2.2&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;asm&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;asm&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;dom4j&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;dom4j&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;1.6.1&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;ehcache&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;ehcache&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;1.2.3&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;hibernate-tools&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;hibernate-tools&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;3.2.3.GA&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;jta&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;jta&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;1.1&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;log4j&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;log4j&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;1.2.11&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;oscache&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;oscache&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;2.1&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;dependency&amp;gt;
 			&amp;lt;groupId&amp;gt;persistence-api&amp;lt;/groupId&amp;gt;
 			&amp;lt;artifactId&amp;gt;persistence-api&amp;lt;/artifactId&amp;gt;
 			&amp;lt;version&amp;gt;1.0&amp;lt;/version&amp;gt;
 		&amp;lt;/dependency&amp;gt;
 		&amp;lt;!-- Hibernate library dependecy end --&amp;gt;
   &amp;lt;/dependencies&amp;gt;
 &amp;lt;/project&amp;gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath. The command line point to the directory C:\HibernateProject\ HibernateManyToManyAnnotations and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<h2>3. Create Model Classes</h2>
<p>As we should be using annotations, we need to only write the model classes:<br />
<em>src\main\java\net\javabeat\hibernate\Person.java</em> and <em>src\main\java\net\javabeat\hibernate\Phone.java</em>.<br />
The contents of the model classes are as below</p>
<p><b>Person.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;
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.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * Model class for Person
 */
@Entity
@Table(name = &amp;quot;Person&amp;quot;, uniqueConstraints = {
		@UniqueConstraint(columnNames = &amp;quot;ID&amp;quot;),
		@UniqueConstraint(columnNames = &amp;quot;NAME&amp;quot;) })
public class Person implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &amp;quot;ID&amp;quot;, unique = true, nullable = false)
	private Long id;

	@Column(name = &amp;quot;NAME&amp;quot;)
	private String name;

	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = &amp;quot;PERSON_PHONE&amp;quot;,
	joinColumns = { @JoinColumn(referencedColumnName = &amp;quot;ID&amp;quot;) },
	inverseJoinColumns = { @JoinColumn(referencedColumnName = &amp;quot;ID&amp;quot;) })
	private Set&amp;lt;Phone&amp;gt; personPhoneNumbers = new HashSet&amp;lt;Phone&amp;gt;();

	public Person(String name, Set&amp;lt;Phone&amp;gt; personPhoneNumbers) {
		super();
		this.name = name;
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public Person() {
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set&amp;lt;Phone&amp;gt; getPersonPhoneNumbers() {
		return personPhoneNumbers;
	}

	public void setPersonPhoneNumbers(Set&amp;lt;Phone&amp;gt; personPhoneNumbers) {
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public void addPhone(Phone phone) {
		this.personPhoneNumbers.add(phone);
	}

}
</pre>
<p><b>Phone.java</b></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import javax.persistence.ManyToMany;

import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = &amp;quot;PHONE&amp;quot;, uniqueConstraints = { @UniqueConstraint(columnNames = &amp;quot;ID&amp;quot;) })
public class Phone implements Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &amp;quot;ID&amp;quot;, unique = true, nullable = false)
	private Long id;

	@Column(name = &amp;quot;CONTACTNUMBER&amp;quot;, unique = true, nullable = false, length = 100)
	private String contactnumber;

	@Column(name = &amp;quot;PHONETYPE&amp;quot;)
	private String phonetype;

	@ManyToMany(mappedBy = &amp;quot;personPhoneNumbers&amp;quot;)
	private Set&amp;lt;Person&amp;gt; persons = new HashSet&amp;lt;Person&amp;gt;();

	public Phone() {

	}

	public Phone(String contactnumber, String phonetype) {
		super();
		this.contactnumber = contactnumber;
		this.phonetype = phonetype;

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getContactnumber() {
		return contactnumber;
	}

	public void setContactnumber(String contactnumber) {
		this.contactnumber = contactnumber;
	}

	public String getPhonetype() {
		return phonetype;
	}

	public void setPhonetype(String phonetype) {
		this.phonetype = phonetype;
	}

	public Set&amp;lt;Person&amp;gt; getPersons() {
		return persons;
	}

	public void setPersons(Set&amp;lt;Person&amp;gt; persons) {
		this.persons = persons;
	}

}
</pre>
<p><b>Details of the above files are as below:</b></p>
<ul>
<li><b>@JoinTable</b> annotation has been used to make the making the association between the tables PERSON and PHONE through PERSON_PHONE table as follows:
<pre class="brush: java; title: ; notranslate">
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = &amp;quot;PERSON_PHONE&amp;quot;,
joinColumns = { @JoinColumn(referencedColumnName = &amp;quot;ID&amp;quot;) },
inverseJoinColumns = { @JoinColumn(referencedColumnName = &amp;quot;ID&amp;quot;) })
private Set&amp;lt;Phone&amp;gt; personPhoneNumbers = new HashSet&amp;lt;Phone&amp;gt;();
</pre>
</li>
<li>As mentioned in the section <b>Many to Many Relationship</b> the JoinTable defines a foreign key to the source object&#8217;s primary key <b>joinColumns</b>, and a foreign key to the target object&#8217;s primary key <b>inverseJoinColumns</b>.</li>
<li>We then map the Phone entity to the Person entity using the <b>mappedBy</b> attribute in Phone.java:
<pre class="brush: java; title: ; notranslate">
@ManyToMany(mappedBy = &amp;quot;personPhoneNumbers&amp;quot;)
private Set&amp;lt;Person&amp;gt; persons = new HashSet&amp;lt;Person&amp;gt;();
</pre>
</li>
</ul>
<h2>4. Adding Hibernate Configuration file</h2>
<p>As a next step let&#8217;s add the <em>hibernate.cfg.xml</em> to the directory:<b>/src/main/resources </b>. Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:</p>
<pre class="brush: java; title: ; notranslate">
&amp;lt;?xml version='1.0' encoding='utf-8'?&amp;gt;
&amp;lt;!DOCTYPE hibernate-configuration PUBLIC
        &amp;quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&amp;quot;
        &amp;quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&amp;quot;&amp;gt;
&amp;lt;hibernate-configuration&amp;gt;
    &amp;lt;session-factory&amp;gt;
         &amp;lt;!-- Database connection settings, Connect to MYSQL --&amp;gt;
        &amp;lt;property name=&amp;quot;dialect&amp;quot;&amp;gt;org.hibernate.dialect.MySQLDialect&amp;lt;/property&amp;gt;
		&amp;lt;property name=&amp;quot;connection.driver_class&amp;quot;&amp;gt;com.mysql.jdbc.Driver&amp;lt;/property&amp;gt;
        &amp;lt;property name=&amp;quot;connection.url&amp;quot;&amp;gt;jdbc:mysql://localhost:3306/manisha&amp;lt;/property&amp;gt;
		 &amp;lt;property name=&amp;quot;connection.username&amp;quot;&amp;gt;root&amp;lt;/property&amp;gt;
        &amp;lt;property name=&amp;quot;connection.password&amp;quot;&amp;gt;root&amp;lt;/property&amp;gt;

        &amp;lt;!-- JDBC connection pool (use the built-in) --&amp;gt;
        &amp;lt;property name=&amp;quot;connection.pool_size&amp;quot;&amp;gt;1&amp;lt;/property&amp;gt;
        &amp;lt;property name=&amp;quot;show_sql&amp;quot;&amp;gt;true&amp;lt;/property&amp;gt;&amp;lt;property name=&amp;quot;format_sql&amp;quot;&amp;gt;true&amp;lt;/property&amp;gt;

        &amp;lt;property name=&amp;quot;cache.provider_class&amp;quot;&amp;gt;org.hibernate.cache.NoCacheProvider&amp;lt;/property&amp;gt;
        &amp;lt;!--create the database schema on startup if required --&amp;gt;
        &amp;lt;property name=&amp;quot;hbm2ddl.auto&amp;quot;&amp;gt;create&amp;lt;/property&amp;gt;
       &amp;lt;mapping class=&amp;quot;net.javabeat.hibernate.Person&amp;quot;&amp;gt;&amp;lt;/mapping&amp;gt;
       &amp;lt;mapping class=&amp;quot;net.javabeat.hibernate.Phone&amp;quot;&amp;gt;&amp;lt;/mapping&amp;gt;

  &amp;lt;/session-factory&amp;gt;
&amp;lt;/hibernate-configuration&amp;gt;
</pre>
<p>In the above file we have set the database connection to MYSQL database . The <i>show_sq</i>l option, if set to true will display all the executed SQL queries on the console. The property <i>hbm2ddl.auto </i>, if set to <i>create</i>, creates the schema, destroying the previous data. At the end of the file we add model classes, Person and Phone to the configuration.</p>
<p><span style="color: #000080;"><strong><span style="text-decoration: underline;">Note :</span> In case you want to use any other database then, you need to change these properties &#8211; &#8220;dialect&#8221;, &#8220;connection.driver_class&#8221;, &#8220;connection.url&#8221;, &#8220;connection.username&#8221;, and &#8220;connection.password&#8221;.</strong></span></p>
<h2>5. Create Utility class</h2>
<p>Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file <b>src\main\java\net\javabeat\hibernate\HibernateUtil.java</b> as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println(&amp;quot;Initial SessionFactory creation failed.&amp;quot; + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}
</pre>
<h2>6. Revise the App class</h2>
<p>Next we will revise the App.java (generated by Maven). This class tests the many-to-many relationship by creating and listing the person names and corresponding phone numbers as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Main class
 *
 */
public class App {
	public static void main(String[] args) {
		System.out
		.println(&amp;quot;Maven + Hibernate + SQL  Many to Many Using Annotations &amp;quot;);
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		App app = new App();

		app.savePersonInfo(&amp;quot;Manisha&amp;quot;);

		app.listPersonInfo();

	}

	public Long savePersonInfo(String personName) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Long personId = null;
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Person person = new Person();
			person.setName(personName);

			Phone ph1 = new Phone();
			Phone ph2 = new Phone();
			ph1.setContactnumber(&amp;quot;4100000&amp;quot;);
			ph1.setPhonetype(&amp;quot;Landline&amp;quot;);

			ph2.setContactnumber(&amp;quot;988000045&amp;quot;);
			ph2.setPhonetype(&amp;quot;Mobile&amp;quot;);
			person.addPhone(ph1);
			person.addPhone(ph2);
			session.save(person);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return personId;
	}

	/*
	 * Lists the person's from database table
	 */
	public void listPersonInfo() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			@SuppressWarnings(&amp;quot;unchecked&amp;quot;)
			List&amp;lt;Person&amp;gt; personList = session.createQuery(&amp;quot;FROM Person&amp;quot;).list();

			System.out.println(&amp;quot;List size: &amp;quot; + (personList).size());
			for (Iterator iterator = personList.iterator(); iterator.hasNext();) {
				Person person = (Person) iterator.next();
				Set&amp;lt;Phone&amp;gt; ph = new HashSet&amp;lt;Phone&amp;gt;();
				ph = person.getPersonPhoneNumbers();
				for (Phone p : ph) {
					System.out.println(&amp;quot;***************************&amp;quot;);
					System.out.println(person.getName());
					System.out.println(&amp;quot; Phone Type: &amp;quot; + p.getPhonetype());
					System.out
					.println(&amp;quot; Phone Number: &amp;quot; + p.getContactnumber());
					System.out.println(&amp;quot;***************************&amp;quot;);
				}
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
</pre>
<p>Here the savePersonInfo() method is used to save a new Person object and Phone object to the database.</p>
<p>The listPersonInfo() method is used to list name of each person in PERSON table and their corresponding phone numbers and type from PHONE table. Here we use Hibernate Query Language (HQL). The query <b>&#8220;from Person&#8221;</b> returns a list of all the data in the PERSON table and their corresponding phone numbers from PHONE table through PERSON_PHONE table (check the select query in the output section ). Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Person and corresponding Phone table and hence display them on the console.</p>
<h2>8. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_annotation_dir_struct.jpg"><img class="alignnone size-medium wp-image-6330" alt="manytomany_annotation_dir_struct" src="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_annotation_dir_struct-147x300.jpg" width="147" height="300" /></a></p>
<h2>9. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class.<br />
Right click on App.java &gt;Run As &gt; Java Application.<br />
On start of each thread, a database schema will be created and the following actions will happen.</p>
<p><b>Output on the console:</b><br />
Following output is displayed on the console:</p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + SQL  Many to Many Using Annotations
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        Person
        (NAME)
    values
        (?)
Hibernate:
    insert
    into
        PHONE
        (CONTACTNUMBER, PHONETYPE)
    values
        (?, ?)
Hibernate:
    insert
    into
        PHONE
        (CONTACTNUMBER, PHONETYPE)
    values
        (?, ?)
Hibernate:
    insert
    into
        PERSON_PHONE
        (persons_ID, personPhoneNumbers_ID)
    values
        (?, ?)
Hibernate:
    insert
    into
        PERSON_PHONE
        (persons_ID, personPhoneNumbers_ID)
    values
        (?, ?)
Hibernate:
    select
        person0_.ID as ID0_,
        person0_.NAME as NAME0_
    from
        Person person0_
List size: 1
Hibernate:
    select
        personphon0_.persons_ID as persons1_1_,
        personphon0_.personPhoneNumbers_ID as personPh2_1_,
        phone1_.ID as ID1_0_,
        phone1_.CONTACTNUMBER as CONTACTN2_1_0_,
        phone1_.PHONETYPE as PHONETYPE1_0_
    from
        PERSON_PHONE personphon0_
    left outer join
        PHONE phone1_
            on personphon0_.personPhoneNumbers_ID=phone1_.ID
    where
        personphon0_.persons_ID=?
***************************
Manisha
 Phone Type: Mobile
 Phone Number: 988000045
***************************
***************************
Manisha
 Phone Type: Landline
 Phone Number: 4100000
***************************
</pre>
<h2>Summary</h2>
<p>In this post we demonstrated many-to-many relation using Java annotation. We initially created a Java project using Maven, made it compatible with eclipse. Then we created model classes using annotations. We then set the values in our main class(App.java), which in turn added the values to respective tables. We also listed the data from the tables. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fdatabase%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/database/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/database/feed/" data-count="vertical" data-text="Database" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-many-to-many-example-annotations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Hibernate Many-To-Many Mapping Example (XML Mapping)</title>
		<link>http://www.javabeat.net/2013/03/hibernate-many-to-many-mapping/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-many-to-many-mapping/#comments</comments>
		<pubDate>Thu, 21 Mar 2013 12:19:11 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6325</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate Many to Many Mapping using XML mapping. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate Many to Many Mapping</strong></span> using <strong>XML mapping</strong>. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a></p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a>.</p>
<h2>Many To Many Relationship</h2>
<p>A ManyToMany relationship in Java is where the source object has an attribute that stores a collection of target objects and (if) those target objects had the inverse relationship back to the source object it would also be a ManyToMany relationship.</p>
<p>All ManyToMany relationships require a <b>JoinTable</b>. The JoinTable is defined using the <b>@JoinTable</b> annotation and <b></b> XML element. The JoinTable defines a foreign key to the source object&#8217;s primary key (joinColumns), and a foreign key to the target object&#8217;s primary key (inverseJoinColumns). Normally the primary key of the JoinTable is the combination of both foreign keys. Let&#8217;s see an example of person and phone relationship as in the below structure:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_tablestruct.jpg"><img class="size-medium wp-image-6331 aligncenter" alt="manytomany_tablestruct" src="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_tablestruct-300x60.jpg" width="300" height="60" /></a></p>
<p>Each person can have more than one phone and each phone can have more than one person associated with it.<br />
<span style="text-decoration: underline;"><strong>Technologies Used:</strong></span><strong></strong></p>
<p>Following are the tools and technologies required for this project:</p>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (<a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">Hibernate Downloads</a>)</li>
<li>MySQL 5 above (<a href="http://dev.mysql.com/downloads/connector/j/5.1.html" target="_blank">MySql Downloads</a>)</li>
</ol>
<h2>1.Environment Setup</h2>
<p>Refer post <a title="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping)</a> for environment setup (follow steps 1,2 and 3). Pass the following command in the step.1, to create a java project using Maven:</p>
<pre class="brush: java; title: ; notranslate">
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateManyToManyXML
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
</pre>
<h2>2. Adding dependencies to pom.xml</h2>
<p>We need to add the Hibernate, <strong>MYSQL</strong> and some other dependencies to the Maven pom.xml as shown below:</p>
<pre class="brush: java; 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.javabeat.hibernate&lt;/groupId&gt;
   &lt;artifactId&gt;HibernateManyToManyXML&lt;/artifactId&gt;
   &lt;packaging&gt;jar&lt;/packaging&gt;
   &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
   &lt;name&gt;HibernateManyToManyXML&lt;/name&gt;
   &lt;url&gt;http://maven.apache.org&lt;/url&gt;
   &lt;dependencies&gt;
     &lt;!-- Hibernate library dependency start --&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate&lt;/artifactId&gt;
 			&lt;version&gt;4.1.9.Final&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;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;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-logging&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
 			&lt;version&gt;1.1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-collections&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
 			&lt;version&gt;3.2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;cglib&lt;/groupId&gt;
 			&lt;artifactId&gt;cglib&lt;/artifactId&gt;
 			&lt;version&gt;2.2&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;asm&lt;/groupId&gt;
 			&lt;artifactId&gt;asm&lt;/artifactId&gt;
 			&lt;version&gt;4.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;ehcache&lt;/groupId&gt;
 			&lt;artifactId&gt;ehcache&lt;/artifactId&gt;
 			&lt;version&gt;1.2.3&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
 			&lt;version&gt;3.2.3.GA&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;jta&lt;/groupId&gt;
 			&lt;artifactId&gt;jta&lt;/artifactId&gt;
 			&lt;version&gt;1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;log4j&lt;/groupId&gt;
 			&lt;artifactId&gt;log4j&lt;/artifactId&gt;
 			&lt;version&gt;1.2.11&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;oscache&lt;/groupId&gt;
 			&lt;artifactId&gt;oscache&lt;/artifactId&gt;
 			&lt;version&gt;2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;persistence-api&lt;/groupId&gt;
 			&lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
 			&lt;version&gt;1.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;!-- Hibernate library dependecy end --&gt;
   &lt;/dependencies&gt;
 &lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath. The command line point to the directory C:\HibernateProject\HibernateManyToManyXML and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<h2>3. Create Model Classes and hibernate mapping files</h2>
<p>Next let’s write Hibernate XML Mapping files to the directory: <b>/src/main/resources</b> . Create the resources directory as follows: Right click on Project &gt; New &gt; Source Folder &gt; Give folder name &#8220;/src/main/resources/&#8221; and click Finish.<br />
Write the file <b>src\main\resources\net\javabeat\hibernate\Person.hbm.xml</b> for the model Person and <b>src\main\resources\net\javabeat\hibernate\Phone.hbm.xml</b> for the model class Phone. The contents of these files are as below:</p>
<p><b>Person.hbm.xml</b></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&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&gt;
	&lt;class name=&quot;net.javabeat.hibernate.Person&quot; table=&quot;person&quot; &gt;
		&lt;id name=&quot;id&quot; type=&quot;java.lang.Long&quot;&gt;
			&lt;column name=&quot;ID&quot; unique=&quot;true&quot;/&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;

		&lt;property name=&quot;name&quot; type=&quot;string&quot;&gt;
			&lt;column name=&quot;NAME&quot; length=&quot;10&quot; not-null=&quot;true&quot; unique=&quot;true&quot; /&gt;
		&lt;/property&gt;
		&lt;set name=&quot;personPhoneNumbers&quot; table=&quot;person_phone&quot; cascade=&quot;all&quot;&gt;
			&lt;key column=&quot;PERSONID&quot; not-null=&quot;true&quot; /&gt;
			&lt;many-to-many column=&quot;PHONEID&quot; class=&quot;net.javabeat.hibernate.Phone&quot; /&gt;
		&lt;/set&gt;

	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<p><b>Phone.hbm.xml</b></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&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&gt;
	&lt;class name=&quot;net.javabeat.hibernate.Phone&quot; table=&quot;phone&quot;&gt;
		&lt;id name=&quot;id&quot; type=&quot;java.lang.Long&quot;&gt;
			&lt;column name=&quot;ID&quot; unique=&quot;true&quot;/&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;contactnumber&quot; type=&quot;string&quot;&gt;
			&lt;column name=&quot;CONTACTNUMBER&quot; /&gt;
		&lt;/property&gt;
		&lt;property name=&quot;phonetype&quot; type=&quot;string&quot;&gt;
			&lt;column name=&quot;PHONETYPE&quot; /&gt;
		&lt;/property&gt;

		&lt;set name=&quot;persons&quot; table=&quot;person_phone&quot;&gt;
            &lt;key column=&quot;PHONEID&quot; /&gt;
            &lt;many-to-many column=&quot;PERSONID&quot; class=&quot;net.javabeat.hibernate.Person&quot; /&gt;
        &lt;/set&gt;
	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<h2>Model classes</h2>
<p>As a next step let&#8217;s create the model classes <em>src\main\java\net\javabeat\hibernate\Person.java</em> and <em>src\main\java\net\javabeat\hibernate\Phone.java</em>. The contents of the model classes are as below</p>
<p><b>Person.java</b></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * Model class for Person
 */
public class Person implements Serializable {
	private Long id;
	private String name;
	private Set&lt;Phone&gt; personPhoneNumbers = new HashSet&lt;Phone&gt;();

	public Person(String name, Set&lt;Phone&gt; personPhoneNumbers) {
		super();
		this.name = name;
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public Person() {
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set&lt;Phone&gt; getPersonPhoneNumbers() {
		return personPhoneNumbers;
	}

	public void setPersonPhoneNumbers(Set&lt;Phone&gt; personPhoneNumbers) {
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public void addPhone(Phone phone) {

		this.personPhoneNumbers.add(phone);
	}

}
</pre>
<p><b>Phone.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Phone implements Serializable {
	private Long id;
	private String contactnumber;
	private String phonetype;
	private Set&lt;Person&gt; persons = new HashSet&lt;Person&gt;();

	public Phone() {

	}

	public Phone(String contactnumber, String phonetype) {
		super();
		this.contactnumber = contactnumber;
		this.phonetype = phonetype;

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getContactnumber() {
		return contactnumber;
	}

	public void setContactnumber(String contactnumber) {
		this.contactnumber = contactnumber;
	}

	public String getPhonetype() {
		return phonetype;
	}

	public void setPhonetype(String phonetype) {
		this.phonetype = phonetype;
	}

	public Set&lt;Person&gt; getPersons() {
		return persons;
	}

	public void setPersons(Set&lt;Person&gt; persons) {
		this.persons = persons;
	}

}
</pre>
<p><b>Details of the above files are as below:</b></p>
<ul>
<li>The many-to-many relationship definition in Person.hbm.xml, the set attribute is defined as follows:
<pre class="brush: java; title: ; notranslate">
&lt;set name=&quot;personPhoneNumbers&quot; table=&quot;person_phone&quot; cascade=&quot;all&quot;&gt;
	&lt;key column=&quot;PERSONID&quot; not-null=&quot;true&quot; /&gt;
	&lt;many-to-many column=&quot;PHONEID&quot; class=&quot;net.javabeat.hibernate.Phone&quot; /&gt;
&lt;/set&gt;
</pre>
<p>The <b>cascade=&#8221;all&#8221;</b> ensures that the INSERT order is appropriate. i.e. the insertion order is in the following fashion PERSON, PHONE and PERSON_PHONE.</li>
<li>The following code in the Phone.hbm.xml, makes the many-to-many association bi-directional.
<pre class="brush: java; title: ; notranslate">
&lt;set name=&quot;persons&quot; table=&quot;person_phone&quot;&gt;
	&lt;key column=&quot;PHONEID&quot; /&gt;
	&lt;many-to-many column=&quot;PERSONID&quot; class=&quot;net.javabeat.hibernate.Person&quot; /&gt;
&lt;/set&gt;
</pre>
<p>Corresponding code in the Phone.java class is as follows:</p>
<pre class="brush: java; title: ; notranslate">
	private Set&lt;Person&gt; persons = new HashSet&lt;Person&gt;();
	public Set&lt;Person&gt; getPersons() {
		return persons;
	}

	public void setPersons(Set&lt;Person&gt; persons) {
		this.persons = persons;
	}
</pre>
</li>
</ul>
<h2>4. Adding Hibernate Configuration file</h2>
<p>As a next step let&#8217;s add the <em>hibernate.cfg.xml</em> to the directory:<b>/src/main/resources </b>. Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:</p>
<pre class="brush: java; 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, Connect to MYSQL --&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&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/manisha&lt;/property&gt;
		 &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;root&lt;/property&gt;

        &lt;!-- JDBC connection pool (use the built-in) --&gt;
        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;&lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;

        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;!--create the database schema on startup if required --&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;create&lt;/property&gt;
        &lt;mapping resource=&quot;net/javabeat/hibernate/Person.hbm.xml&quot;&gt;&lt;/mapping&gt;
       &lt;mapping resource=&quot;net/javabeat/hibernate/Phone.hbm.xml&quot;&gt;&lt;/mapping&gt;

  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>In the above file we have set the database connection to MYSQL database . The <i>show_sq</i>l option, if set to true will display all the executed SQL queries on the console. The property <i>hbm2ddl.auto </i>, if set to <i>create</i>, creates the schema, destroying the previous data. At the end of the file we add the Person.hbm.xml and Phone.hbm.xml files to the configuration.</p>
<p><span style="color: #000080;"><strong><span style="text-decoration: underline;">Note :</span> In case you want to use any other database then, you need to change these properties &#8211; &#8220;dialect&#8221;, &#8220;connection.driver_class&#8221;, &#8220;connection.url&#8221;, &#8220;connection.username&#8221;, and &#8220;connection.password&#8221;.</strong></span></p>
<h2>5. Create Utility class</h2>
<p>Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file <b>src\main\java\net\javabeat\hibernate\HibernateUtil.java</b> as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = 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>6. Revise the App class</h2>
<p>Next we will revise the App.java (generated by Maven). This class tests the many-to-many relationship by creating and listing the person names and corresponding phone numbers as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Main class
 *
 */
public class App {
	public static void main(String[] args) {
		System.out.println(&quot;Maven + Hibernate + SQL  Many to Many XML Mapping &quot;);
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		App app = new App();

		app.savePersonInfo(&quot;Manisha&quot;);

		app.listPersonInfo();

	}

	public Long savePersonInfo(String personName) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Long personId = null;
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Person person = new Person();
			person.setName(personName);

			Phone ph1 = new Phone();
			Phone ph2 = new Phone();
			ph1.setContactnumber(&quot;4100000&quot;);
			ph1.setPhonetype(&quot;Landline&quot;);

			ph2.setContactnumber(&quot;988000045&quot;);
			ph2.setPhonetype(&quot;Mobile&quot;);
			person.addPhone(ph1);
			person.addPhone(ph2);
			session.save(person);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return personId;
	}

	/*
	 * Lists the person's from database table
	 */
	public void listPersonInfo() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			@SuppressWarnings(&quot;unchecked&quot;)
			List&lt;Person&gt; personList = session.createQuery(&quot;FROM Person&quot;).list();

			System.out.println(&quot;List size: &quot; + (personList).size());
			for (Iterator iterator = personList.iterator(); iterator.hasNext();) {
				Person person = (Person) iterator.next();
				Set&lt;Phone&gt; ph = new HashSet&lt;Phone&gt;();
				ph = person.getPersonPhoneNumbers();
				for (Phone p : ph) {
					System.out.println(&quot;***************************&quot;);
					System.out.println(person.getName());
					System.out.println(&quot; Phone Type: &quot; + p.getPhonetype());
					System.out.println(&quot; Phone Number: &quot; + p.getContactnumber());
					System.out.println(&quot;***************************&quot;);
				}
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
</pre>
<p>Here the savePersonInfo() method is used to save a new Person object and Phone object to the database.</p>
<p>The listPersonInfo() method is used to list name of each person in PERSON table and their corresponding phone numbers and type from PHONE table. Here we use Hibernate Query Language (HQL). The query <b>&#8220;from Person&#8221;</b> returns a list of all the data in the PERSON table and their corresponding phone numbers from PHONE table through the table PERSON_PHONE(check the select query in the output section). Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Person and corresponding Phone table and hence display them on the console.</p>
<h2>8. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_xmlmapping_dir_struct.jpg"><img class="size-medium wp-image-6329 aligncenter" alt="manytomany_xmlmapping_dir_struct" src="http://www.javabeat.net/wp-content/uploads/2013/03/manytomany_xmlmapping_dir_struct-138x300.jpg" width="138" height="300" /></a></p>
<h2>9. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class. Right click on App.java &gt;Run As &gt; Java Application. On start of each thread, a database schema will be created and the following actions will happen.</p>
<p><b>Output on the console:</b><br />
Following output is displayed on the console:</p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + SQL  Many to Many XML Mapping
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        person
        (NAME)
    values
        (?)
Hibernate:
    insert
    into
        phone
        (CONTACTNUMBER, PHONETYPE)
    values
        (?, ?)
Hibernate:
    insert
    into
        phone
        (CONTACTNUMBER, PHONETYPE)
    values
        (?, ?)
Hibernate:
    insert
    into
        person_phone
        (PERSONID, PHONEID)
    values
        (?, ?)
Hibernate:
    insert
    into
        person_phone
        (PERSONID, PHONEID)
    values
        (?, ?)
Hibernate:
    select
        person0_.ID as ID0_,
        person0_.NAME as NAME0_
    from
        person person0_
List size: 1
Hibernate:
    select
        personphon0_.PERSONID as PERSONID1_,
        personphon0_.PHONEID as PHONEID1_,
        phone1_.ID as ID2_0_,
        phone1_.CONTACTNUMBER as CONTACTN2_2_0_,
        phone1_.PHONETYPE as PHONETYPE2_0_
    from
        person_phone personphon0_
    left outer join
        phone phone1_
            on personphon0_.PHONEID=phone1_.ID
    where
        personphon0_.PERSONID=?
***************************
Manisha
 Phone Type: Landline
 Phone Number: 4100000
***************************
***************************
Manisha
 Phone Type: Mobile
 Phone Number: 988000045
***************************
</pre>
<h2>Summary</h2>
<p>In this post we demonstrated Many-to-Many relation using hibernate mapping files. We initially created a Java project using Maven, made it compatible with eclipse. Then we created hibernate mapping files and created the corresponding model classes (using join table association). We then set the values in our main class(App.java), which in turn added the values to respective tables. We also listed the data from the tables. In the next post we shall see an example of Hibernate Many-to-Many mapping(using Annotations).If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-many-to-many-mapping/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate One-To-Many Mapping Example Using Annotations</title>
		<link>http://www.javabeat.net/2013/03/hibernate-one-to-many-example-annotations/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-one-to-many-example-annotations/#comments</comments>
		<pubDate>Tue, 19 Mar 2013 13:01:26 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6301</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate one to Many Mapping using Java Annotations. In my previous article I have explained Hibernate one to Many Mapping using XML. The main difference between these two examples would be the hibernate configuration files and annotations. Otherwise both the articles trying the same [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate one to Many Mapping</strong></span> using <strong>Java Annotations</strong>. In my previous article I have explained <a href="http://www.javabeat.net/2013/03/hibernate-one-to-many-mapping-example/"><strong>Hibernate one to Many Mapping</strong> using <strong>XML</strong></a>. The main difference between these two examples would be the hibernate configuration files and annotations. Otherwise both the articles trying the same example.</p>
<p>We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a></p>
<ul>
<li><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><a class="downloadlink" href="http://www.javabeat.net/downloads/HibernateOneToManyAnnotations.zip" title=" downloaded 14 times" >HibernateOneToManyAnnotations (14)</a><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a>.</li>
</ul>
<h2>One To Many Relationship</h2>
<p>Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one. An example is the relationship between Person and Phone.<br />
Consider the following relationship:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_relation.jpg"><img class="size-medium wp-image-6288 aligncenter" alt="onetomany_relation" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_relation-300x61.jpg" width="300" height="61" /></a></p>
<p>According to the relationship each Person can have a any number of phone numbers. But each phone number will be associated with only one person. Hence we will need two tables namely PERSON and PHONE to create this relation. <span style="text-decoration: underline; color: #000080;"><strong>In Hibernate, one-to-many relationship between entities can be created by 2 different techniques</strong></span>. These techniques are:</p>
<ol>
<ol>
<li><span style="text-decoration: underline;"><b>Using foreign key association</b>:</span> In this association, we can have a foreign key column in PHONE table i.i PERSONID. This column will refer to primary key of PERSON table. This way no two phone numbers can be associated with multiple persons. Obviously, phone number needs to be unique for enforcing this restriction. The example below in this post demonstrates this asscociation. The relational model is shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_foreignkey.jpg"><img class="size-medium wp-image-6287 aligncenter" alt="onetomany_foreignkey" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_foreignkey-300x87.jpg" width="300" height="87" /></a></li>
<li><span style="text-decoration: underline;"><b>Using a common join table</b>: </span>In this association, we can have a common join table lets say PERSON_PHONE. This table will have two column i.e. PERSON_ID which will be foreign key referring to primary key in PERSON table and similarly PHONE_ID which will be foreign key referring to primary key of PHONE table.<br />
The relational model is shown below:</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_usingjointable.jpg"><img class="size-medium wp-image-6289 aligncenter" alt="onetomany_usingjointable" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_usingjointable-300x61.jpg" width="300" height="61" /></a></li>
</ol>
</ol>
<p><span style="text-decoration: underline;"><strong>Technologies Used:</strong></span><strong></strong></p>
<p>Following are the tools and technologies required for this project:</p>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (<a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">Hibernate Downloads</a>)</li>
<li>MySQL 5 above (<a href="http://dev.mysql.com/downloads/connector/j/5.1.html" target="_blank">MySql Downloads</a>)</li>
</ol>
<h2>1.Environment Setup</h2>
<p>Refer post <a title="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping)</a> for environment setup (follow steps 1,2 and 3). Pass the following command in the step.1, to create a java project using Maven:</p>
<pre class="brush: java; title: ; notranslate">
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateOneToManyAnnotations
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
</pre>
<h2>2. Adding dependencies to pom.xml</h2>
<p>We need to add the Hibernate, <strong>MYSQL</strong> and some other dependencies to the Maven pom.xml as shown below:</p>
<pre class="brush: java; 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.javabeat.hibernate&lt;/groupId&gt;
   &lt;artifactId&gt; HibernateOneToManyAnnotations&lt;/artifactId&gt;
   &lt;packaging&gt;jar&lt;/packaging&gt;
   &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
   &lt;name&gt; HibernateOneToManyAnnotations&lt;/name&gt;
   &lt;url&gt;http://maven.apache.org&lt;/url&gt;
   &lt;dependencies&gt;
     &lt;!-- Hibernate library dependency start --&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate&lt;/artifactId&gt;
 			&lt;version&gt;4.1.9.Final&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;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;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-logging&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
 			&lt;version&gt;1.1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-collections&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
 			&lt;version&gt;3.2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;cglib&lt;/groupId&gt;
 			&lt;artifactId&gt;cglib&lt;/artifactId&gt;
 			&lt;version&gt;2.2&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;asm&lt;/groupId&gt;
 			&lt;artifactId&gt;asm&lt;/artifactId&gt;
 			&lt;version&gt;4.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;ehcache&lt;/groupId&gt;
 			&lt;artifactId&gt;ehcache&lt;/artifactId&gt;
 			&lt;version&gt;1.2.3&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
 			&lt;version&gt;3.2.3.GA&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;jta&lt;/groupId&gt;
 			&lt;artifactId&gt;jta&lt;/artifactId&gt;
 			&lt;version&gt;1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;log4j&lt;/groupId&gt;
 			&lt;artifactId&gt;log4j&lt;/artifactId&gt;
 			&lt;version&gt;1.2.11&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;oscache&lt;/groupId&gt;
 			&lt;artifactId&gt;oscache&lt;/artifactId&gt;
 			&lt;version&gt;2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;persistence-api&lt;/groupId&gt;
 			&lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
 			&lt;version&gt;1.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;!-- Hibernate library dependecy end --&gt;
   &lt;/dependencies&gt;
 &lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath. The command line point to the directory C:\HibernateProject\ HibernateOneToManyAnnotations and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<h2>3. Create Model Classes</h2>
<p>As we sould be using annotations, we need to only write the model classes:<br />
<em>src\main\java\net\javabeat\hibernate\Person.java</em> and <em>src\main\java\net\javabeat\hibernate\Phone.java</em>.<br />
The contents of the model classes are as below</p>
<p><b>Person.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;
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.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * Model class for Person
 */
@Entity
@Table(name=&quot;Person&quot;
  , uniqueConstraints = {
  @UniqueConstraint(columnNames = &quot;ID&quot;),
  @UniqueConstraint(columnNames = &quot;NAME&quot;) })

public class Person implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &quot;ID&quot;, unique = true, nullable = false)
	private Long id;

	@Column(name = &quot;NAME&quot;)
	private String name;

	@OneToMany(cascade = CascadeType.ALL, mappedBy = &quot;person&quot;)
	private Set&lt;Phone&gt; personPhoneNumbers = new HashSet&lt;Phone&gt;();

	public Person(String name, Set&lt;Phone&gt; personPhoneNumbers) {
		super();
		this.name = name;
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public Person() {
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set&lt;Phone&gt; getPersonPhoneNumbers() {
		return personPhoneNumbers;
	}

	public void setPersonPhoneNumbers(Set&lt;Phone&gt; personPhoneNumbers) {
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public void addPhone(Phone phone) {
		phone.setPerson(this);
		this.personPhoneNumbers.add(phone);
	}

}
</pre>
<p><b>Phone.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = &quot;PHONE&quot;, uniqueConstraints = { @UniqueConstraint(columnNames = &quot;ID&quot;) })
public class Phone implements Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &quot;ID&quot;, unique = true, nullable = false)
	private Long id;

	@Column(name = &quot;CONTACTNUMBER&quot;, unique = true, nullable = false, length = 100)
	private String contactnumber;

	@Column(name = &quot;PHONETYPE&quot;)
	private String phonetype;

	@ManyToOne
	@JoinColumn(name = &quot;personId&quot;)
	private Person person;

	public Phone() {

	}

	public Phone(String contactnumber, String phonetype) {
		super();
		this.contactnumber = contactnumber;
		this.phonetype = phonetype;

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getContactnumber() {
		return contactnumber;
	}

	public void setContactnumber(String contactnumber) {
		this.contactnumber = contactnumber;
	}

	public String getPhonetype() {
		return phonetype;
	}

	public void setPhonetype(String phonetype) {
		this.phonetype = phonetype;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

}

</pre>
<p><b>Details of the above files are as below:</b></p>
<ul>
<li>In the file Person.java, we have made the one to many association using the annotation @OneToMany(cascade = CascadeType.ALL, mappedBy = &#8220;person&#8221;). Here <b>mappedBy</b> attribute is used to define the field that &#8220;owns&#8221; the relation on the owning side (the side that holds the foreign key i.e. the Many side in a one-to-many. Here it is the person field in Phone entity). <b>@ManyToOne</b> annotation is used in the Phone class.</li>
<li>The @JoinColumn annotation should be defined on the owning side only (in our case it is the Phone entity).</li>
</ul>
<h2>4. Adding Hibernate Configuration file</h2>
<p>As a next step let&#8217;s add the <em>hibernate.cfg.xml</em> to the directory:<b>/src/main/resources </b>. Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; 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, Connect to MYSQL --&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&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/manisha&lt;/property&gt;
		 &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;root&lt;/property&gt;

        &lt;!-- JDBC connection pool (use the built-in) --&gt;
        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;&lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;

        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;!--create the database schema on startup if required --&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;create&lt;/property&gt;
       &lt;mapping class=&quot;net.javabeat.hibernate.Person&quot;&gt;&lt;/mapping&gt;
       &lt;mapping class=&quot;net.javabeat.hibernate.Phone&quot;&gt;&lt;/mapping&gt;

  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>In the above file we have set the database connection to MYSQL database . The <i>show_sq</i>l option, if set to true will display all the executed SQL queries on the console. The property <i>hbm2ddl.auto </i>, if set to <i>create</i>, creates the schema, destroying the previous data. At the end of the file we add model classes, Person and Phone to the configuration.</p>
<p><span style="color: #000080;"><strong><span style="text-decoration: underline;">Note :</span> In case you want to use any other database then, you need to change these properties &#8211; &#8220;dialect&#8221;, &#8220;connection.driver_class&#8221;, &#8220;connection.url&#8221;, &#8220;connection.username&#8221;, and &#8220;connection.password&#8221;.</strong></span></p>
<h2>5. Create Utility class</h2>
<p>Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file <b>src\main\java\net\javabeat\hibernate\HibernateUtil.java</b> as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = 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. Revise the App class</h2>
<p>Next we will revise the App.java (generated by Maven). This class tests the one-to-many relationship by creating and listing the person names and corresponding phone numbers as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Main class
 *
 */
public class App {
	public static void main(String[] args) {
		System.out
				.println(&quot;Maven + Hibernate + SQL  One to Many Using Annotations &quot;);
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		App app = new App();

		app.savePersonInfo(&quot;Manisha&quot;);

		app.listPersonInfo();

	}

	public Long savePersonInfo(String personName) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Long personId = null;
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Person person = new Person();
			person.setName(personName);

			Phone ph1 = new Phone();
			Phone ph2 = new Phone();
			ph1.setContactnumber(&quot;4100000&quot;);
			ph1.setPhonetype(&quot;Landline&quot;);

			ph2.setContactnumber(&quot;988000045&quot;);
			ph2.setPhonetype(&quot;Mobile&quot;);
			person.addPhone(ph1);
			person.addPhone(ph2);
			session.save(person);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return personId;
	}

	/*
	 * Lists the person's from database table
	 */
	public void listPersonInfo() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			@SuppressWarnings(&quot;unchecked&quot;)
			List&lt;Person&gt; personList = session.createQuery(&quot;FROM Person&quot;).list();

			System.out.println(&quot;List size: &quot; + (personList).size());
			for (Iterator iterator = personList.iterator(); iterator.hasNext();) {
				Person person = (Person) iterator.next();
				Set&lt;Phone&gt; ph = new HashSet&lt;Phone&gt;();
				ph = person.getPersonPhoneNumbers();
				for (Phone p : ph) {
					System.out.println(&quot;***************************&quot;);
					System.out.println(person.getName());
					System.out.println(&quot; Phone Type: &quot; + p.getPhonetype());
					System.out
					.println(&quot; Phone Number: &quot; + p.getContactnumber());
					System.out.println(&quot;***************************&quot;);
				}
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
</pre>
<p>Here the savePersonInfo() method is used to save a new Person object and Phone object to the database.</p>
<p>The listPersonInfo() method is used to list name of each person in PERSON table and their corresponding phone numbers and type from PHONE table. Here we use Hibernate Query Language (HQL). The query <b>&#8220;from Person&#8221;</b> returns a list of all the data in the PERSON table and their corresponding phone numbers from PHONE table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Person and corresponding Phone table and hence display them on the console.</p>
<h2>8. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomanyannotation_dir_struct.jpg"><img class="size-medium wp-image-6307 aligncenter" alt="onetomanyannotation_dir_struct" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomanyannotation_dir_struct-136x300.jpg" width="136" height="300" /></a></p>
<h2>9. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class.<br />
Right click on App.java &gt;Run As &gt; Java Application.<br />
On start of each thread, a database schema will be created and the following actions will happen.</p>
<p><b>Output on the console:</b><br />
Following output is displayed on the console:</p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + SQL  One to Many Using Annotations
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        Person
        (NAME)
    values
        (?)
Hibernate:
    insert
    into
        PHONE
        (CONTACTNUMBER, personId, PHONETYPE)
    values
        (?, ?, ?)
Hibernate:
    insert
    into
        PHONE
        (CONTACTNUMBER, personId, PHONETYPE)
    values
        (?, ?, ?)
Hibernate:
    select
        person0_.ID as ID0_,
        person0_.NAME as NAME0_
    from
        Person person0_
List size: 1
Hibernate:
    select
        personphon0_.personId as personId1_,
        personphon0_.ID as ID1_,
        personphon0_.ID as ID1_0_,
        personphon0_.CONTACTNUMBER as CONTACTN2_1_0_,
        personphon0_.personId as personId1_0_,
        personphon0_.PHONETYPE as PHONETYPE1_0_
    from
        PHONE personphon0_
    where
        personphon0_.personId=?
***************************
Manisha
 Phone Type: Mobile
 Phone Number: 988000045
***************************
***************************
Manisha
 Phone Type: Landline
 Phone Number: 4100000
***************************
</pre>
<h2>Using a Common Join Table</h2>
<p>This technique uses a join table to store the associations between Person and Phone entities (as seen in the entity relation diagram above).<br />
We use @JoinTable annotation to create the one-to-many relationship between the Person and Phone entities. Following needs to be added to the Person entity:</p>
<pre class="brush: java; title: ; notranslate">
@OneToMany
    @JoinTable(
            name=&quot;Person_Phone&quot;,
            joinColumns = @JoinColumn( name=&quot;person_id&quot;),
            inverseJoinColumns = @JoinColumn( name=&quot;phone_id&quot;)
    )
    public Set&lt;Phone&gt; getPersonPhoneNumbers() {
</pre>
<p>@manytoone annotation need not be set in the Phone entity, hence making it unidirectional.</p>
<h2>Summary</h2>
<ul>
<li><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><a class="downloadlink" href="http://www.javabeat.net/downloads/HibernateOneToManyAnnotations.zip" title=" downloaded 14 times" >HibernateOneToManyAnnotations (14)</a></a></li>
</ul>
<blockquote><p>In my previous article I have explained <a href="http://www.javabeat.net/2013/03/hibernate-one-to-many-mapping-example/"><strong>Hibernate one to Many Mapping</strong> using <strong>Java Annotations</strong></a>. The main difference between these two examples would be the hibernate configuration files and annotations. Otherwise both the articles trying the same example.</p></blockquote>
<p>In this post we demonstrated one-to-many relation using Java annotation. We discussed about various techniques of one-to-many associations. We initially created a Java project using Maven, made it compatible with eclipse. Then we created model classes using annotations (foreign key association). We then set the values in our main class(App.java), which in turn added the values to respective tables. We also listed the data from the tables. In the next post we shall see an example of Hibernate Many-to-Many mapping(using XML mpping).If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-one-to-many-example-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate One-To-Many Mapping Example (XML Mapping)</title>
		<link>http://www.javabeat.net/2013/03/hibernate-one-to-many-mapping-example/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-one-to-many-mapping-example/#comments</comments>
		<pubDate>Tue, 19 Mar 2013 00:56:37 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6282</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate one to Many Mapping using XML mapping. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate one to Many Mapping</strong></span> using <strong>XML mapping</strong>. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a></p>
<ul>
<li><a class="downloadlink" href="http://www.javabeat.net/downloads/20130319-HibernateOneToManyXML.zip" title=" downloaded 13 times" >Source Code Download for HibernateOneToManyXML (13)</a></li>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a>.</p>
<h2>One To Many Relationship</h2>
<p>Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one. An example is the relationship between Person and Phone. Consider the following relationship:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_relation.jpg"><img class="size-medium wp-image-6288 aligncenter" alt="onetomany_relation" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_relation-300x61.jpg" width="300" height="61" /></a></p>
<p>According to the relationship each Person can have a any number of phone numbers. But each phone number will be associated with only one person. Hence we will need two tables namely PERSON and PHONE to create this relation. <span style="text-decoration: underline; color: #000080;"><strong>In Hibernate, one-to-many relationship between entities can be created by 2 different techniques</strong></span>. These techniques are:</p>
<ol>
<ol>
<li><span style="text-decoration: underline;"><b>Using foreign key association</b>:</span> In this association, we can have a foreign key column in PHONE table i.i PERSONID. This column will refer to primary key of PERSON table. This way no two phone numbers can be associated with multiple persons. Obviously, phone number needs to be unique for enforcing this restriction. The example below in this post demonstrates this association. The relational model is shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_foreignkey.jpg"><img class="alignnone size-medium wp-image-6287" alt="onetomany_foreignkey" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_foreignkey-300x87.jpg" width="300" height="87" /></a></li>
<li><span style="text-decoration: underline;"><b>Using a common join table</b>: </span>In this association, we can have a common join table lets say PERSON_PHONE. This table will have two column i.e. PERSON_ID which will be foreign key referring to primary key in PERSON table and similarly PHONE_ID which will be foreign key referring to primary key of PHONE table. The relational model is shown below:</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_usingjointable.jpg"><img class="alignnone size-medium wp-image-6289" alt="onetomany_usingjointable" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_usingjointable-300x61.jpg" width="300" height="61" /></a></li>
</ol>
</ol>
<p><span style="text-decoration: underline;"><strong>Technologies Used:</strong></span><strong></strong></p>
<p>Following are the tools and technologies required for this project:</p>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (<a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">Hibernate Downloads</a>)</li>
<li>MySQL 5 above (<a href="http://dev.mysql.com/downloads/connector/j/5.1.html" target="_blank">MySql Downloads</a>)</li>
</ol>
<h2>1.Environment Setup</h2>
<p>Refer post <a title="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping)</a> for environment setup (follow steps 1,2 and 3). Pass the following command in the step.1, to create a java project using Maven:</p>
<pre class="brush: java; title: ; notranslate">
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateOneToManyXML
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
</pre>
<h2>2. Adding dependencies to pom.xml</h2>
<p>We need to add the Hibernate, <strong>MYSQL</strong> and some other dependencies to the Maven pom.xml as shown below:</p>
<pre class="brush: java; 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.javabeat.hibernate&lt;/groupId&gt;
   &lt;artifactId&gt;HibernateOneToManyXML&lt;/artifactId&gt;
   &lt;packaging&gt;jar&lt;/packaging&gt;
   &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
   &lt;name&gt;HibernateOneToManyXML&lt;/name&gt;
   &lt;url&gt;http://maven.apache.org&lt;/url&gt;
   &lt;dependencies&gt;
     &lt;!-- Hibernate library dependency start --&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate&lt;/artifactId&gt;
 			&lt;version&gt;4.1.9.Final&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;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;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-logging&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
 			&lt;version&gt;1.1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-collections&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
 			&lt;version&gt;3.2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;cglib&lt;/groupId&gt;
 			&lt;artifactId&gt;cglib&lt;/artifactId&gt;
 			&lt;version&gt;2.2&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;asm&lt;/groupId&gt;
 			&lt;artifactId&gt;asm&lt;/artifactId&gt;
 			&lt;version&gt;4.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;ehcache&lt;/groupId&gt;
 			&lt;artifactId&gt;ehcache&lt;/artifactId&gt;
 			&lt;version&gt;1.2.3&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
 			&lt;version&gt;3.2.3.GA&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;jta&lt;/groupId&gt;
 			&lt;artifactId&gt;jta&lt;/artifactId&gt;
 			&lt;version&gt;1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;log4j&lt;/groupId&gt;
 			&lt;artifactId&gt;log4j&lt;/artifactId&gt;
 			&lt;version&gt;1.2.11&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;oscache&lt;/groupId&gt;
 			&lt;artifactId&gt;oscache&lt;/artifactId&gt;
 			&lt;version&gt;2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;persistence-api&lt;/groupId&gt;
 			&lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
 			&lt;version&gt;1.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;!-- Hibernate library dependecy end --&gt;
   &lt;/dependencies&gt;
 &lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath. The command line point to the directory C:\HibernateProject\HibernateOneToManyXML and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<h2>3. Create Model Classes and hibernate mapping files</h2>
<p>Next let’s write Hibernate XML Mapping files to the directory: <b>/src/main/resources</b> . Create the resources directory as follows: Right click on Project &gt; New &gt; Source Folder &gt; Give folder name &#8220;/src/main/resources/&#8221; and click Finish. Write the file <b>src\main\resources\net\javabeat\hibernate\Person.hbm.xml</b> for the model Person and <b>src\main\resources\net\javabeat\hibernate\Phone.hbm.xml</b> for the model class Phone. The contents of these files are as below:</p>
<p><b>Person.hbm.xml</b></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&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&gt;
	&lt;class name=&quot;net.javabeat.hibernate.Person&quot; table=&quot;person&quot;&gt;
		&lt;id name=&quot;id&quot; type=&quot;java.lang.Long&quot;&gt;
			&lt;column name=&quot;ID&quot; /&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;

		&lt;property name=&quot;name&quot; type=&quot;string&quot;&gt;
			&lt;column name=&quot;NAME&quot; length=&quot;10&quot; not-null=&quot;true&quot; unique=&quot;true&quot; /&gt;
		&lt;/property&gt;
		&lt;set name=&quot;personPhoneNumbers&quot; table=&quot;phone&quot; cascade=&quot;all&quot;
			inverse=&quot;true&quot;&gt;
			&lt;key column=&quot;PERSONID&quot; not-null=&quot;true&quot; /&gt;
			&lt;one-to-many class=&quot;net.javabeat.hibernate.Phone&quot; /&gt;
		&lt;/set&gt;

	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<p><b>Phone.hbm.xml</b></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&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&gt;
	&lt;class name=&quot;net.javabeat.hibernate.Phone&quot; table=&quot;PHONE&quot;&gt;
		&lt;id name=&quot;id&quot; type=&quot;java.lang.Long&quot;&gt;
			&lt;column name=&quot;ID&quot; /&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;contactnumber&quot; type=&quot;string&quot;&gt;
			&lt;column name=&quot;CONTACTNUMBER&quot; /&gt;
		&lt;/property&gt;
		&lt;property name=&quot;phonetype&quot; type=&quot;string&quot;&gt;
			&lt;column name=&quot;PHONETYPE&quot; /&gt;
		&lt;/property&gt;
		&lt;many-to-one name=&quot;person&quot; class=&quot;net.javabeat.hibernate.Person&quot;
			not-null=&quot;true&quot;&gt;
			&lt;column name=&quot;PERSONID&quot; /&gt;
		&lt;/many-to-one&gt;

	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<h2>Model classes</h2>
<p>As a next step let&#8217;s create the model classes <em>src\main\java\net\javabeat\hibernate\Person.java</em> and <em>src\main\java\net\javabeat\hibernate\Phone.java</em>. The contents of the model classes are as below</p>
<p><b>Person.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * Model class for Person
 */
public class Person implements Serializable {
	private Long id;
	private String name;
	private Set&lt;Phone&gt; personPhoneNumbers = new HashSet&lt;Phone&gt;();

	public Person(String name, Set&lt;Phone&gt; personPhoneNumbers) {
		super();
		this.name = name;
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public Person() {
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set&lt;Phone&gt; getPersonPhoneNumbers() {
		return personPhoneNumbers;
	}

	public void setPersonPhoneNumbers(Set&lt;Phone&gt; personPhoneNumbers) {
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public void addPhone(Phone phone) {
		phone.setPerson(this);
		this.personPhoneNumbers.add(phone);
	}

}
</pre>
<p><b>Phone.java</b></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

public class Phone implements Serializable {
	private Long id;
	private String contactnumber;
	private String phonetype;
	private Person person;

	public Phone() {

	}

	public Phone(String contactnumber, String phonetype) {
		super();
		this.contactnumber = contactnumber;
		this.phonetype = phonetype;

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getContactnumber() {
		return contactnumber;
	}

	public void setContactnumber(String contactnumber) {
		this.contactnumber = contactnumber;
	}

	public String getPhonetype() {
		return phonetype;
	}

	public void setPhonetype(String phonetype) {
		this.phonetype = phonetype;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

}
</pre>
<p><b>Details of the above files are as below:</b></p>
<ul>
<li>The one-to-many association between person and phone in the following manner (added to Person.hbm.xml):
<pre class="brush: java; title: ; notranslate">
&lt;set name=&quot;personPhoneNumbers&quot; table=&quot;phone&quot; cascade=&quot;all&quot; inverse=&quot;true&quot;&gt;
    &lt;key column=&quot;PERSONID&quot; not-null=&quot;true&quot; /&gt;
    &lt;one-to-many class=&quot;net.javabeat.hibernate.Phone&quot; /&gt;
&lt;/set&gt;
</pre>
<p><b>cascade=&#8221;all&#8221;</b> is used to specify that all operations should be cascaded along the association.<br />
<b>inverse=&#8221;true&#8221;</b> it tells Hibernate that both mappings(Person and Phone) map to the same single FK relationship. Otherwise, Hibernate will try to update both sides separately, and not in any order. So it might try to insert a child before the parent is inserted, and the database will throw an error. Hence hibernate will not issue sql statements when parent is modified. SQL statements will be issued to the DB only when the association is modified at the child end.</li>
</ul>
<p>Corresponding code in model class (Person.java) is as follows:</p>
<pre class="brush: java; title: ; notranslate">
private Set&lt;Phone&gt; personPhoneNumbers = new HashSet&lt;Phone&gt;();

public Set&lt;Phone&gt; getPersonPhoneNumbers() {
		return personPhoneNumbers;
	}

	public void setPersonPhoneNumbers(Set&lt;Phone&gt; personPhoneNumbers) {
		this.personPhoneNumbers = personPhoneNumbers;
	}

	public void addPhone(Phone phone) {
		phone.setPerson(this);
		this.personPhoneNumbers.add(phone);
}
</pre>
<ul>
<li>In Phone.hbm.xml file the following code is added:
<pre class="brush: java; title: ; notranslate">
&lt;many-to-one name=&quot;person&quot; class=&quot;net.javabeat.hibernate.Person&quot;
	not-null=&quot;true&quot;&gt;
	&lt;column name=&quot;PERSONID&quot; /&gt;
&lt;/many-to-one&gt;
</pre>
<p>Corresponding code in Phone.java is:</p>
<pre class="brush: java; title: ; notranslate">
private Person person;

public Person getPerson() {
	return person;
}

public void setPerson(Person person) {
	this.person = person;
}
</pre>
</li>
<li>The following addPhone() method in the Person.java, makes sure that personid field in the PHONE table is not set to null.
<pre class="brush: java; title: ; notranslate">
public void addPhone(Phone phone) {
	phone.setPerson(this);
	this.phones.add(phone);
}
</pre>
</li>
</ul>
<h2>4. Adding Hibernate Configuration file</h2>
<p>As a next step let&#8217;s add the <em>hibernate.cfg.xml</em> to the directory:<b>/src/main/resources </b>. Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:</p>
<pre class="brush: java; 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, Connect to MYSQL --&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&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/manisha&lt;/property&gt;
		 &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;root&lt;/property&gt;

        &lt;!-- JDBC connection pool (use the built-in) --&gt;
        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;

        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;!--create the database schema on startup if required --&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;create&lt;/property&gt;
        &lt;mapping resource=&quot;net/javabeat/hibernate/Person.hbm.xml&quot;&gt;&lt;/mapping&gt;
        &lt;mapping resource=&quot;net/javabeat/hibernate/Phone.hbm.xml&quot;&gt;&lt;/mapping&gt;

  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>In the above file we have set the database connection to MYSQL database . The <i>show_sq</i>l option, if set to true will display all the executed SQL queries on the console. The property <i>hbm2ddl.auto </i>, if set to <i>create</i>, creates the schema, destroying the previous data. At the end of the file we add the Person.hbm.xml and Phone.hbm.xml files to the configuration.</p>
<p><span style="color: #000080;"><strong><span style="text-decoration: underline;">Note :</span> In case you want to use any other database then, you need to change these properties &#8211; &#8220;dialect&#8221;, &#8220;connection.driver_class&#8221;, &#8220;connection.url&#8221;, &#8220;connection.username&#8221;, and &#8220;connection.password&#8221;.</strong></span></p>
<h2>5. Create Utility class</h2>
<p>Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file <b>src\main\java\net\javabeat\hibernate\HibernateUtil.java</b> as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = 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>6. Revise the App class</h2>
<p>Next we will revise the App.java (generated by Maven). This class tests the one-to-many relationship by creating and listing the person names and corresponding phone numbers as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Main class
 *
 */
public class App {
	public static void main(String[] args) {
		System.out.println(&quot;Maven + Hibernate + SQL  One to Many XML Mapping &quot;);
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		App app = new App();

		app.savePersonInfo(&quot;Manisha&quot;);

		app.listPersonInfo();

	}

	public Long savePersonInfo(String personName) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Long personId = null;
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Person person = new Person();
			person.setName(personName);

			Phone ph1 = new Phone();
			Phone ph2 = new Phone();
			ph1.setContactnumber(&quot;4100000&quot;);
			ph1.setPhonetype(&quot;Landline&quot;);

			ph2.setContactnumber(&quot;988000045&quot;);
			ph2.setPhonetype(&quot;Mobile&quot;);
			person.addPhone(ph1);
			person.addPhone(ph2);
			session.save(person);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return personId;
	}

	/*
	 * Lists the person's from database table
	 */
	public void listPersonInfo() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			@SuppressWarnings(&quot;unchecked&quot;)
			List&lt;Person&gt; personList = session.createQuery(&quot;FROM Person&quot;).list();

			System.out.println(&quot;List size: &quot; + (personList).size());
			for (Iterator iterator = personList.iterator(); iterator.hasNext();) {
				Person person = (Person) iterator.next();
				Set&lt;Phone&gt; ph = new HashSet&lt;Phone&gt;();
				ph = person.getPersonPhoneNumbers();
				for (Phone p : ph) {
					System.out.println(&quot;***************************&quot;);
					System.out.println(person.getName());
					System.out.println(&quot; Phone Type: &quot; + p.getPhonetype());
					System.out.println(&quot; Phone Number: &quot; + p.getContactnumber());
					System.out.println(&quot;***************************&quot;);
				}
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
</pre>
<p>Here the savePersonInfo() method is used to save a new Person object and Phone object to the database.</p>
<p>The listPersonInfo() method is used to list name of each person in PERSON table and their corresponding phone numbers and type from PHONE table. Here we use Hibernate Query Language (HQL). The query <b>&#8220;from Person&#8221;</b> returns a list of all the data in the PERSON table and their corresponding phone numbers from PHONE table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Person and corresponding Phone table and hence display them on the console.</p>
<h2>8. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_xml_dir_struct.jpg"><img class="size-medium wp-image-6286 aligncenter" alt="onetomany_xml_dir_struct" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetomany_xml_dir_struct-160x300.jpg" width="160" height="300" /></a></p>
<h2>9. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class. Right click on App.java &gt;Run As &gt; Java Application. On start of each thread, a database schema will be created and the following actions will happen.</p>
<p><b>Output on the console:</b><br />
Following output is displayed on the console:</p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + SQL  One to Many XML Mapping
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        person
        (NAME)
    values
        (?)
Hibernate:
    insert
    into
        PHONE
        (CONTACTNUMBER, PHONETYPE, PERSONID)
    values
        (?, ?, ?)
Hibernate:
    insert
    into
        PHONE
        (CONTACTNUMBER, PHONETYPE, PERSONID)
    values
        (?, ?, ?)
Hibernate:
    select
        person0_.ID as ID0_,
        person0_.NAME as NAME0_
    from
        person person0_
List size: 1
Hibernate:
    select
        personphon0_.PERSONID as PERSONID1_,
        personphon0_.ID as ID1_,
        personphon0_.ID as ID1_0_,
        personphon0_.CONTACTNUMBER as CONTACTN2_1_0_,
        personphon0_.PHONETYPE as PHONETYPE1_0_,
        personphon0_.PERSONID as PERSONID1_0_
    from
        PHONE personphon0_
    where
        personphon0_.PERSONID=?
***************************
Manisha
 Phone Type: Landline
 Phone Number: 4100000
***************************
***************************
Manisha
 Phone Type: Mobile
 Phone Number: 988000045
***************************

</pre>
<h2>Using a Common Join Table</h2>
<p>This technique uses a join table to store the associations between Person and Phone entities. We use <b>many-to-many</b> element to create the one-to-many relationship between the Person and Phone entities. Since a Person can have any number of phone numbers we use a collection to hold the values. In this case we use Set. Many-to-many element is usually used to create many-to-many relationship, here we place the <b>unique</b> constraint on the PHONE_ID column, this makes the relationship one-to-many.</p>
<pre class="brush: java; title: ; notranslate">
&lt;set name=&quot;personPhoneNumbers&quot; table=&quot;PHONE&quot; cascade=&quot;all&quot;&gt;
&lt;key column=&quot;PERSON_ID&quot; /&gt;
&lt;many-to-many column=&quot;PHONE_ID&quot; unique=&quot;true&quot; class=&quot;net.javabeat.hibernate.Phone&quot; /&gt;
&lt;/set&gt;
</pre>
<h2>Summary</h2>
<ul>
<li><a class="downloadlink" href="http://www.javabeat.net/downloads/20130319-HibernateOneToManyXML.zip" title=" downloaded 13 times" >Source Code Download for HibernateOneToManyXML (13)</a></li>
</ul>
<p>In this post we demonstrated one-to-many relation using hibernate mapping files. We discussed about various techniques of one-to-many associations. We initially created a Java project using Maven, made it compatible with eclipse. Then we created hibernate mapping files and created the corresponding model classes (foreign key association). We then set the values in our main class(App.java), which in turn added the values to respective tables. We also listed the data from the tables. In the next post we shall see an example of Hibernate One-to-Many mapping(using Annotations).If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-one-to-many-mapping-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hibernate One-To-One Mapping Example Using Java Annotations</title>
		<link>http://www.javabeat.net/2013/03/hibernate-one-to-one-mapping-annotations/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-one-to-one-mapping-annotations/#comments</comments>
		<pubDate>Sat, 16 Mar 2013 14:52:32 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6171</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate one to one Mapping using Java Annotations. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate one to one Mapping</strong></span> using <strong>Java Annotations</strong>. We will first create a Java project using Maven and then will add Hibernate on it. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a></p>
<ul>
<li><a class="downloadlink" href="http://www.javabeat.net/downloads/20130319-HibernateOneToOneAnnotation.zip" title=" downloaded 8 times" >Source Code Download for HibernateOneToOneAnnotation (8)</a></li>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a>.</p>
<h2>One To One Relationship</h2>
<p>A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. Consider the following relationship:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/hibernate_onetoone_mapping.jpg"><img class="size-medium wp-image-6151 aligncenter" alt="hibernate_onetoone_mapping" src="http://www.javabeat.net/wp-content/uploads/2013/03/hibernate_onetoone_mapping-300x121.jpg" width="300" height="121" /></a></p>
<p>According to the relationship each Person should have a unique address. Hence we will need two tables namely PERSON and ADDRESS to create this relation. <span style="text-decoration: underline; color: #000080;"><strong>In Hibernate, one-to-one relationship between entities can be created by 3 different techniques</strong></span>. In each technique though <b>@OneToOne</b> annotation has to be used. These techniques are:</p>
<ol>
<ol>
<li><span style="text-decoration: underline;"><b>Using shared primary key</b>:</span> In this technique, hibernate will ensure that it will use a common primary key value in both the tables. This way primary key of entity PERSON can safely be assumed the primary key of entity ADDRESS also. The example demonstrated in this post is using shared primary key. The relational model is shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_pk_sharing.jpg"><img class="size-medium wp-image-6183 aligncenter" alt="onetoone_pk_sharing" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_pk_sharing-300x123.jpg" width="300" height="123" /></a></li>
<li><span style="text-decoration: underline;"><b>Using foreign key association</b>:</span> In this association, a foreign key column is created in the owner entity. For example, if we make PERSON as owner entity, then a extra column &#8220;ADDRESSID&#8221; will be created in PERSON table. This column will store the foreign key for ADDRESS table. The relational model is shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_foreing-key.jpg"><img class="size-medium wp-image-6184 aligncenter" alt="onetoone_foreing key" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_foreing-key-300x138.jpg" width="300" height="138" /></a></li>
<li><span style="text-decoration: underline;"><b>Using a common join table</b>: </span>In this association, the join table will have two foreign key columns (i.e) it will have both the primary key columns from the two entity tables (for example PERSONID and ADDRESSID from PERSON and ADDRESS entity tables respectively). One of the foreign keys will serve as the primary key for the join table. An unique constraint will be applied on the remaining foreign key column and hence both the foreign key columns will not have the duplicate values.<br />
The relational model is shown below:</li>
</ol>
</ol>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_join-table.jpg"><img class="size-medium wp-image-6185 aligncenter" alt="onetoone_join table" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_join-table-300x96.jpg" width="300" height="96" /></a></p>
<p><span style="text-decoration: underline;"><strong>Technologies Used:</strong></span><strong></strong></p>
<p>Following are the tools and technologies required for this project:</p>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (<a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">Hibernate Downloads</a>)</li>
<li>MySQL 5 above (<a href="http://dev.mysql.com/downloads/connector/j/5.1.html" target="_blank">MySql Downloads</a>)</li>
</ol>
<h2>1.Environment Setup</h2>
<p>Refer post <a title="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL – Example Project (XML Mapping)</a> for environment setup (follow steps 1,2 and 3). Pass the following command in the step.1, to create a java project using Maven:</p>
<pre class="brush: java; title: ; notranslate">
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateOneToOneAnnotation
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
</pre>
<h2>2. Adding dependencies to pom.xml</h2>
<p>We need to add the Hibernate, <strong>MYSQL</strong> and some other dependencies to the Maven pom.xml as shown below:</p>
<pre class="brush: java; 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.javabeat.hibernate&lt;/groupId&gt;
 	&lt;artifactId&gt;HibernateOneToOneAnnotation&lt;/artifactId&gt;
 	&lt;packaging&gt;jar&lt;/packaging&gt;
 	&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
 	&lt;name&gt;HibernateOneToOneAnnotation&lt;/name&gt;
 	&lt;url&gt;http://maven.apache.org&lt;/url&gt;
 	&lt;dependencies&gt;
 		&lt;!-- Hibernate library dependency start --&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate&lt;/artifactId&gt;
 			&lt;version&gt;4.1.9.Final&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;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;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-logging&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
 			&lt;version&gt;1.1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;commons-collections&lt;/groupId&gt;
 			&lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
 			&lt;version&gt;3.2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;cglib&lt;/groupId&gt;
 			&lt;artifactId&gt;cglib&lt;/artifactId&gt;
 			&lt;version&gt;2.2&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;asm&lt;/groupId&gt;
 			&lt;artifactId&gt;asm&lt;/artifactId&gt;
 			&lt;version&gt;4.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;dom4j&lt;/groupId&gt;
 			&lt;artifactId&gt;dom4j&lt;/artifactId&gt;
 			&lt;version&gt;1.6.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;ehcache&lt;/groupId&gt;
 			&lt;artifactId&gt;ehcache&lt;/artifactId&gt;
 			&lt;version&gt;1.2.3&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
 			&lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
 			&lt;version&gt;3.2.3.GA&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;jta&lt;/groupId&gt;
 			&lt;artifactId&gt;jta&lt;/artifactId&gt;
 			&lt;version&gt;1.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;log4j&lt;/groupId&gt;
 			&lt;artifactId&gt;log4j&lt;/artifactId&gt;
 			&lt;version&gt;1.2.11&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;oscache&lt;/groupId&gt;
 			&lt;artifactId&gt;oscache&lt;/artifactId&gt;
 			&lt;version&gt;2.1&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;dependency&gt;
 			&lt;groupId&gt;persistence-api&lt;/groupId&gt;
 			&lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
 			&lt;version&gt;1.0&lt;/version&gt;
 		&lt;/dependency&gt;
 		&lt;!-- Hibernate library dependecy end --&gt;
 	&lt;/dependencies&gt;
&lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath. The command line point to the directory C:\HibernateProject\HibernateOneToManyXML and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<h2>3. Create Model Classes (Shared primary key technique)</h2>
<p>As a next step let&#8217;s create the model classes<br />
<em>src\main\java\net\javabeat\hibernate\Person.java</em> and <em>src\main\java\net\javabeat\hibernate\Address.java</em> using Annotations. <b> @PrimaryKeyJoinColumn</b> is the main annotation to be used in shared primary key technique. The model classes are as below</p>
<p><b>Person.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * Model class for Person
 */
@Entity
@Table(name = &quot;PERSON&quot;, uniqueConstraints = { @UniqueConstraint(columnNames = &quot;personId&quot;) })
public class Person implements Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &quot;personId&quot;)
	private Long personId;

	@Column(name = &quot;name&quot;)
	private String name;

	@OneToOne(cascade = CascadeType.ALL)
	@PrimaryKeyJoinColumn
	private Address address;

	public Person() {
	}

	public Person(String name, Address address) {
		super();
		this.name = name;
		this.address = address;
	}

	public Long getPersonId() {
		return personId;
	}

	public void setPersonId(Long personId) {
		this.personId = personId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

}
</pre>
<p>In the above file we see that we have used @PrimaryKeyJoinColumn for the Address entity. Following if a piece of code from the above file:</p>
<pre class="brush: java; title: ; notranslate">
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Address address;
</pre>
<p><b>Address.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = &quot;ADDRESS&quot;, uniqueConstraints = { @UniqueConstraint(columnNames = &quot;personId&quot;) })
public class Address implements Serializable {
	@Id
	@Column(name = &quot;personId&quot;, unique = true, nullable = false)
	@GeneratedValue(generator = &quot;gen&quot;)
	@GenericGenerator(name = &quot;gen&quot;, strategy = &quot;foreign&quot;,
        parameters = @Parameter(name = &quot;property&quot;, value = &quot;person&quot;))
	private Long personId;

	@Column(name = &quot;street&quot;)
	private String street;

	@Column(name = &quot;city&quot;)
	private String city;

	@Column(name = &quot;state&quot;)
	private String state;

	@Column(name = &quot;zipcode&quot;)
	private String zipcode;

	@OneToOne(mappedBy = &quot;address&quot;, cascade = CascadeType.ALL)
	private Person person;

	public Address() {

	}

	public Address(String street, String city, String state, String zipcode) {
		this.street = street;
		this.city = city;
		this.state = state;
		this.zipcode = zipcode;

	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getZipcode() {
		return zipcode;
	}

	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public Long getPersonId() {
		return personId;
	}

	public void setPersonId(Long personId) {
		this.personId = personId;
	}

}
</pre>
<p>Here we see that Address entity will remain dependent on owner entity for the mapping. Following is a piece of code from the above file:</p>
<pre class="brush: java; title: ; notranslate">
@OneToOne(mappedBy = &quot;address&quot;, cascade = CascadeType.ALL)
	private Person person;
</pre>
<h2>4. Adding Hibernate Configuration file</h2>
<p>As a next step let&#8217;s add the <em>hibernate.cfg.xml</em> to the directory:<b>/src/main/resources </b>. Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; 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, Connect to MYSQL --&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&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/manisha&lt;/property&gt;
		 &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;root&lt;/property&gt;

        &lt;!-- JDBC connection pool (use the built-in) --&gt;
        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;

        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;!--create the database schema on startup if required --&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;create&lt;/property&gt;
       &lt;mapping class=&quot;net.javabeat.hibernate.Person&quot;&gt;&lt;/mapping&gt;
       &lt;mapping class=&quot;net.javabeat.hibernate.Address&quot;&gt;&lt;/mapping&gt;
   &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>In the above file we have set the database connection to MYSQL database . The <i>show_sq</i>l option, if set to true will display all the executed SQL queries on the console. The property <i>hbm2ddl.auto </i>, if set to <i>create</i>, creates the schema, destroying the previous data.</p>
<p><span style="color: #000080;"><strong><span style="text-decoration: underline;">Note :</span> In case you want to use any other database then, you need to change these properties &#8211; &#8220;dialect&#8221;, &#8220;connection.driver_class&#8221;, &#8220;connection.url&#8221;, &#8220;connection.username&#8221;, and &#8220;connection.password&#8221;.</strong></span></p>
<p>Also we have added the Annotation based entity classes Person.java and Address.java to the above file.</p>
<h2>5. Create Utility class</h2>
<p>Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file <b>src\main\java\net\javabeat\hibernate\HibernateUtil.java</b> as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = 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. Revise the App class</h2>
<p>Next we will revise the App.java (generated by Maven). This class tests the one-to-one relationship by creating and listing the person names and corresponding addresses as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Main class
 *
 */
public class App {
    public static void main(String[] args) {
        System.out.println(&quot;Maven + Hibernate + MYSQL One to One Mapping Annotations&quot;);
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        App app = new App();

        Address address1 = new Address(&quot;M.G.Road&quot;, &quot;Bangalore&quot;, &quot;Karnataka&quot;,
                &quot;56000&quot;);
        Address address2 = new Address(&quot;Tilak Road&quot;, &quot;Pune&quot;, &quot;Maharashtra&quot;,
                &quot;411207&quot;);

        app.savePersonInfo(&quot;Jiya&quot;, address1);
        app.savePersonInfo(&quot;Manisha&quot;, address2);

        app.listPersonInfo();

    }

    public Long savePersonInfo(String personName, Address address) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Long personId = null;
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Person person = new Person(personName, address);

            address.setPerson(person);
            session.save(person);

            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return personId;
    }

    /*
     * Lists the person's from database table
     */
    public void listPersonInfo() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            @SuppressWarnings(&quot;unchecked&quot;)
            List&lt;Person&gt; personList = session.createQuery(&quot;from Person&quot;).list();
            for (Iterator&lt;Person&gt; iterator = personList.iterator(); iterator
                    .hasNext();) {
                Person person = (Person) iterator.next();
                System.out.println(person.getName());
                System.out.println(person.getAddress().getStreet() + &quot; &quot;
                        + person.getAddress().getCity() + &quot; &quot;
                        + person.getAddress().getState() + &quot; &quot;
                        + person.getAddress().getZipcode());
            }
            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

}
</pre>
<p>Here the savePersonInfo() method is used to save a new Person object and Address object to the database. In the savePersonInfo() method a new object of the Person class is created and the name value and address is set. The personId value is auto generated so the value need not be set here. We then save the Person object to the Address object. The session.save() method is used to persist the value in the database and once the value is saved, the id value (Primary key) is returned. Once the object is saved, the transaction is committed. If any exception occurs then the transaction is rolledback. The transaction ends either through commit or rollback action. Once the transaction ends the session is closed.</p>
<p>The listPersonInfo() method is used to list name of each person in PERSON table and their corresponding addresses from ADDRESS table. Here we use Hibernate Query Language (HQL). The query <b>&#8220;from Person&#8221;</b> returns a list of all the data in the PERSON table and their corresponding addresses from ADDRESS table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Person and corresponding Address table and hence display them on the console.</p>
<h2>8. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetooneannotation_dir_struct.jpg"><img class="size-medium wp-image-6186 aligncenter" alt="onetooneannotation_dir_struct" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetooneannotation_dir_struct-170x300.jpg" width="170" height="300" /></a></p>
<h2>9. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class.<br />
Right click on App.java &gt;Run As &gt; Java Application.<br />
On start of each thread, a database schema will be created and the following actions will happen.</p>
<p><b>Output on the console:</b><br />
Following output is displayed on the console:</p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + MYSQL One to One Mapping Annotations
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        PERSON
        (name)
    values
        (?)
Hibernate:
    insert
    into
        ADDRESS
        (city, state, street, zipcode, personId)
    values
        (?, ?, ?, ?, ?)
Hibernate:
    insert
    into
        PERSON
        (name)
    values
        (?)
Hibernate:
    insert
    into
        ADDRESS
        (city, state, street, zipcode, personId)
    values
        (?, ?, ?, ?, ?)
Hibernate:
    select
        person0_.personId as personId0_,
        person0_.name as name0_
    from
        PERSON person0_
Hibernate:
    select
        address0_.personId as personId1_2_,
        address0_.city as city1_2_,
        address0_.state as state1_2_,
        address0_.street as street1_2_,
        address0_.zipcode as zipcode1_2_,
        person1_.personId as personId0_0_,
        person1_.name as name0_0_,
        address2_.personId as personId1_1_,
        address2_.city as city1_1_,
        address2_.state as state1_1_,
        address2_.street as street1_1_,
        address2_.zipcode as zipcode1_1_
    from
        ADDRESS address0_
    left outer join
        PERSON person1_
            on address0_.personId=person1_.personId
    left outer join
        ADDRESS address2_
            on person1_.personId=address2_.personId
    where
        address0_.personId=?
Hibernate:
    select
        address0_.personId as personId1_2_,
        address0_.city as city1_2_,
        address0_.state as state1_2_,
        address0_.street as street1_2_,
        address0_.zipcode as zipcode1_2_,
        person1_.personId as personId0_0_,
        person1_.name as name0_0_,
        address2_.personId as personId1_1_,
        address2_.city as city1_1_,
        address2_.state as state1_1_,
        address2_.street as street1_1_,
        address2_.zipcode as zipcode1_1_
    from
        ADDRESS address0_
    left outer join
        PERSON person1_
            on address0_.personId=person1_.personId
    left outer join
        ADDRESS address2_
            on person1_.personId=address2_.personId
    where
        address0_.personId=?
Jiya
M.G.Road Bangalore Karnataka 56000
Manisha
Tilak Road Pune Maharashtra 411207
</pre>
<h2>Using Foreign Key Technique</h2>
<p>In such a association, refer the Address entity in Person class as follows:</p>
<pre class="brush: java; title: ; notranslate">
@OneToOne
@JoinColumn(name=&quot;addressId&quot;)
private Address address;
</pre>
<p>If no <b>@JoinColumn</b> is declared on the owner entity, the defaults apply. A join column(s) will be created in the owner entity table and its name will be the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side.</p>
<p>In a bidirectional relationship, one of the sides has to be the owner entity. The owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute <b>mappedBy</b> is used. <b>mappedBy</b> refers to the property name of the association on the owner side. Following is the example code:</p>
<pre class="brush: java; title: ; notranslate">
@OneToOne(mappedBy=&quot;address&quot;)
private Person person;
</pre>
<h2>Using a Common Join Table</h2>
<p>In this technique, main annotation to be used is <b>@JoinTable</b>. This annotation is used to define the new table name (this is mandatory) and foreign keys from both of the tables. Folllowing is the example code:</p>
<pre class="brush: java; title: ; notranslate">
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name=&quot;PERSON_ADDRESS&quot;, joinColumns = @JoinColumn(name=&quot;personId&quot;),
inverseJoinColumns = @JoinColumn(name=&quot;addressId&quot;))
private Address address;
</pre>
<p><b>@JoinTable</b> annotation is used in Person class. It declares that a new table PERSON_ADDRESS will be created with two columns personId (primary key of PERSON table) and addressId (primary key of ADDRESS table).</p>
<h2>Summary</h2>
<ul>
<li><a class="downloadlink" href="http://www.javabeat.net/downloads/20130319-HibernateOneToOneAnnotation.zip" title=" downloaded 8 times" >Source Code Download for HibernateOneToOneAnnotation (8)</a></li>
</ul>
<p>In this post we demonstrated one-to-one relation using Java annotations. We discussed about various techniques of one-to-one associations using annotations. We initially created a Java project using Maven, made it compatible with eclipse. Then we used annotations and created the model classes (primary key sharing association). We then set the values in our main class(App.java), which in turn added the values to respective tables. We also listed the data from the tables. In the next post we shall see an example of Hibernate One-to-Many mapping(XML mapping).If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-one-to-one-mapping-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate One-To-One Mapping(XML mapping)</title>
		<link>http://www.javabeat.net/2013/03/hibernate-one-to-one-mapping/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-one-to-one-mapping/#comments</comments>
		<pubDate>Fri, 15 Mar 2013 08:08:26 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6148</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate one to one Mapping. We shall use HSQL as the database and Maven for creating the project and making it compatible with eclipse. We will first create a Java project using Maven and then will add Hibernate on it. HSQL database is [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate one to one Mapping</strong></span>. We shall use HSQL as the database and Maven for creating the project and making it compatible with eclipse. We will first create a Java project using Maven and then will add Hibernate on it. <strong>HSQL database</strong> is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a></p>
<ul>
<li><a class="downloadlink" href="http://www.javabeat.net/downloads/20130319-HibernateOneToOneXML.zip" title=" downloaded 6 times" >Source Code Download for HibernateOneToOneXML (6)</a></li>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/hibernate-mapping.png"><img class="aligncenter size-full wp-image-6208" alt="hibernate-mapping" src="http://www.javabeat.net/wp-content/uploads/2013/03/hibernate-mapping.png" width="588" height="35" /></a></p>
<h2>One To One Relationship</h2>
<p>A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. Consider the following relationship:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/hibernate_onetoone_mapping.jpg"><img class="size-medium wp-image-6151 aligncenter" alt="hibernate_onetoone_mapping" src="http://www.javabeat.net/wp-content/uploads/2013/03/hibernate_onetoone_mapping-300x121.jpg" width="300" height="121" /></a></p>
<p>According to the relationship each Person should have a unique address. Hence we will need two tables namely PERSON and ADDRESS to create this relation. The relational model is shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_table_relation.jpg"><img class="size-medium wp-image-6152 aligncenter" alt="onetoone_table_relation" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_table_relation-300x136.jpg" width="300" height="136" /></a></p>
<p>Hence following points would be included in our example project demonstrating One-to-One relationship :</p>
<ol>
<li>We will write two POJO classes (Person.java and Address.java ) and corresponding mapping files would be <em>Person.hbm.xml</em> and <em>Address.hbm.xml</em> respectively. Here the relation is, one address is assigned for one person only.</li>
<li>To achieve one to one relationship, both tables have the same PERSON_ID as primary key. In ADDRESS table, PERSON_ID is the primary key and also a foreign key to PERSON table. This is the common way of define &#8220;one-to-one&#8221; table relationship.</li>
</ol>
<h2>Pre-Requisites</h2>
<p>Following are the tools and technologies required for this project:</p>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (Download from <a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">http://hibernate.org/downloads</a>)</li>
<li>HsqlDB (Download from <a href="http://hsqldb.org/" target="_blank">http://hsqldb.org/</a>)</li>
</ol>
<h2>1. Generating Maven Java project compatible with Eclipse</h2>
<p>We will create a Java project using Maven (Refer post <a title="Creating Simple Java Project Using Apache Maven" href="http://www.javabeat.net/2013/02/creating-simple-java-project-using-apache-maven/" target="_blank">Creating Simple Java Project Using Apache Maven</a>). Open the command line window and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateOneToOneXML
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
</pre>
<p>On execution of the above command, a java project <b>HibernateOneToOneXML</b> is created (In our case we have created it in the directory C:\HibernateProject). This java project already has a directory structure (as explained in the post (Refer post <a title="Creating Simple Java Project Using Apache Maven" href="http://www.javabeat.net/2013/02/creating-simple-java-project-using-apache-maven/" target="_blank">Creating Simple Java Project Using Apache Maven</a>). To make this project compatible with eclipse, let&#8217;s execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<h2>2. Import project into Eclipse</h2>
<p>Open Eclipse and import the above Java project as explained below:</p>
<p><b>File &gt; Import&#8230; &gt; General &gt; Existing Projects into Workspace &gt; Choose above Java project</b></p>
<p><b>Build-path settings</b><br />
Goto Window &gt; Preferences&#8230; &gt; Java &gt; Build Path &gt; Classpath Variables &gt;</p>
<ul>
<li>Define new variable M2_REPO pointing to your local maven repository. (In our case it is:C:/Documents and Settings/Manisha/.m2/repository).</li>
<li>Define new variable HSQLDB pointing to the hsqldb.jar. (C:/tools/hsqldb-2.2.9/hsqldb/lib/hsqldb.jar).</li>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/classpath_setting.jpg"><img class="size-medium wp-image-6039 aligncenter" alt="classpath_setting" src="http://www.javabeat.net/wp-content/uploads/2013/03/classpath_setting-300x145.jpg" width="300" height="145" /></a></p>
<h2>3. Adding the Hibernate and HSQLDB Dependency to pom.xml</h2>
<p>We need to add the Hibernate, <strong>HSQLDB</strong> and some other dependencies to the Maven pom.xml as shown below:</p>
<pre class="brush: java; 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.javabeat.hibernate&lt;/groupId&gt;
 &lt;artifactId&gt;HibernateOneToOneXML&lt;/artifactId&gt;
 &lt;packaging&gt;jar&lt;/packaging&gt;
 &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
 &lt;name&gt;HibernateOneToOneXML&lt;/name&gt;
 &lt;url&gt;http://maven.apache.org&lt;/url&gt;
 &lt;dependencies&gt;
   &lt;dependency&gt;
     &lt;groupId&gt;junit&lt;/groupId&gt;
     &lt;artifactId&gt;junit&lt;/artifactId&gt;
     &lt;version&gt;3.8.1&lt;/version&gt;
     &lt;scope&gt;test&lt;/scope&gt;
   &lt;/dependency&gt;
&lt;!-- Hibernate library dependecy start --&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
     &lt;artifactId&gt;hibernate&lt;/artifactId&gt;
     &lt;version&gt;4.1.9.Final&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;org.hsqldb&lt;/groupId&gt;
     &lt;artifactId&gt;hsqldb&lt;/artifactId&gt;
     &lt;version&gt;2.2.9&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;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-logging&lt;/groupId&gt;
     &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
     &lt;version&gt;1.1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-collections&lt;/groupId&gt;
     &lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
     &lt;version&gt;3.2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;cglib&lt;/groupId&gt;
     &lt;artifactId&gt;cglib&lt;/artifactId&gt;
     &lt;version&gt;2.2&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;asm&lt;/groupId&gt;
     &lt;artifactId&gt;asm&lt;/artifactId&gt;
     &lt;version&gt;4.0&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;ehcache&lt;/groupId&gt;
      &lt;artifactId&gt;ehcache&lt;/artifactId&gt;
      &lt;version&gt;1.2.3&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
      &lt;version&gt;3.2.3.GA&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;jta&lt;/groupId&gt;
      &lt;artifactId&gt;jta&lt;/artifactId&gt;
      &lt;version&gt;1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;log4j&lt;/groupId&gt;
      &lt;artifactId&gt;log4j&lt;/artifactId&gt;
      &lt;version&gt;1.2.11&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;oscache&lt;/groupId&gt;
      &lt;artifactId&gt;oscache&lt;/artifactId&gt;
      &lt;version&gt;2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;persistence-api&lt;/groupId&gt;
      &lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
      &lt;version&gt;1.0&lt;/version&gt;
   &lt;/dependency&gt;
  &lt;!-- Hibernate library dependecy end --&gt;
&lt;/dependencies&gt;
&lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath.</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<h2>4. Create Model Classes</h2>
<p>As a next step let&#8217;s create the model classes<br />
<em>src\main\java\net\javabeat\hibernate\Person.java</em> and <em>src\main\java\net\javabeat\hibernate\Address.java</em> as below:</p>
<p><b>Person.java</b></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

/**
 * Model class for Person
 */
public class Person implements Serializable {
	private Long personId;
	private String name;

	private Address address;

	public Person() {
	}

	public Long getPersonId() {
		return personId;
	}

	public void setPersonId(Long personId) {
		this.personId = personId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

}
</pre>
<p><b>Address.java</b></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

public class Address implements Serializable {
	private String street;
	private String city;
	private String state;
	private String zipcode;
	private Person person;
	private Long personId;

	public Address() {

	}

	public Address(String street, String city, String state, String zipcode) {
		this.street = street;
		this.city = city;
		this.state = state;
		this.zipcode = zipcode;

	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getZipcode() {
		return zipcode;
	}

	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public Long getPersonId() {
		return personId;
	}

	public void setPersonId(Long personId) {
		this.personId = personId;
	}

}
</pre>
<h2>Hibernate Mapping Files</h2>
<p>Next let&#8217;s write a Hibernate XML Mapping files to the directory:<b>/src/main/resources </b>. Create the <i>resources</i> directory as follows: Right click on Project &gt; New &gt; Source Folder &gt; Give folder name &#8220;/src/main/resources/&#8221; and click Finish.<br />
Write the file <b>src\main\resources\net\javabeat\hibernate\Person.hbm.xml</b> for the model Person and<br />
<b>src\main\resources\net\javabeat\hibernate\Address.hbm.xml</b> for the model class Address.<br />
The contents of these files are as below:</p>
<p><b>Person.hbm.xml</b></p>
<pre class="brush: java; title: ; notranslate">
 &lt;?xml version=&quot;1.0&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&gt;
 	&lt;class name=&quot;net.javabeat.hibernate.Person&quot; table=&quot;person&quot;&gt;
 		&lt;id name=&quot;personId&quot; type=&quot;java.lang.Long&quot;&gt;
 			&lt;column name=&quot;PERSON_ID&quot; /&gt;
 			&lt;generator class=&quot;native&quot; /&gt;
 		&lt;/id&gt;

 		&lt;property name=&quot;name&quot; type=&quot;string&quot;&gt;
 			&lt;column name=&quot;NAME&quot; length=&quot;10&quot; not-null=&quot;true&quot; unique=&quot;true&quot; /&gt;
 		&lt;/property&gt;
 		&lt;one-to-one name=&quot;address&quot; class=&quot;net.javabeat.hibernate.Address&quot;
 			cascade=&quot;save-update&quot;&gt;&lt;/one-to-one&gt;
 	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<p><b>Address.hbm.xml</b></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&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&gt;
	&lt;class name=&quot;net.javabeat.hibernate.Address&quot; table=&quot;address&quot;&gt;
		&lt;meta attribute=&quot;class-description&quot;&gt;This class contains the address of each person
			details.&lt;/meta&gt;
		&lt;id name=&quot;personId&quot; type=&quot;java.lang.Long&quot;&gt;
			&lt;column name=&quot;PERSON_ID&quot; /&gt;
			&lt;generator class=&quot;foreign&quot;&gt;
                &lt;param name=&quot;property&quot;&gt;person&lt;/param&gt;
            &lt;/generator&gt;

		&lt;/id&gt;
		&lt;one-to-one name=&quot;person&quot; class=&quot;net.javabeat.hibernate.Person&quot;
			constrained=&quot;true&quot;&gt;&lt;/one-to-one&gt;
		&lt;property name=&quot;street&quot; column=&quot;ADDRESS_STREET&quot; type=&quot;string&quot;
			length=&quot;250&quot; /&gt;
		&lt;property name=&quot;city&quot; column=&quot;ADDRESS_CITY&quot; type=&quot;string&quot;
			length=&quot;50&quot; /&gt;
		&lt;property name=&quot;state&quot; column=&quot;ADDRESS_STATE&quot; type=&quot;string&quot;
			length=&quot;50&quot; /&gt;
		&lt;property name=&quot;zipcode&quot; column=&quot;ADDRESS_ZIPCODE&quot; type=&quot;string&quot;
			length=&quot;10&quot; /&gt;

	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<p>In the above hibernate mapping file we are implementing One-to-One relationship. For both the model classes we are using a single primary key personId. In Adress hbm file we have defined a foreign identifier generator so that primary it uses primary key of Person table.</p>
<h2>5. Adding Hibernate Configuration file</h2>
<p>As a next step let&#8217;s add the <em>hibernate.cfg.xml</em> to the directory:<b>/src/main/resources </b>. Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:</p>
<pre class="brush: java; 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, Connect to HSQL, IN Memory  --&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.HSQLDialect&lt;/property&gt;
		&lt;property name=&quot;connection.driver_class&quot;&gt;org.hsqldb.jdbcDriver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:hsqldb:mem:test&lt;/property&gt;
		 &lt;property name=&quot;connection.username&quot;&gt;sa&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

        &lt;!-- JDBC connection pool (use the built-in) --&gt;
        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;&lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;

        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;!--create the database schema on startup if required --&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;
       &lt;!-- &lt;mapping class=&quot;entities.Subscriber&quot;/&gt; --&gt;
       &lt;mapping resource=&quot;net/javabeat/hibernate/Person.hbm.xml&quot;&gt;&lt;/mapping&gt;
       &lt;mapping resource=&quot;net/javabeat/hibernate/Address.hbm.xml&quot;&gt;&lt;/mapping&gt;

  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;

</pre>
<p>In the above file we have set the database connection to HSQL-In memory database (<i>mem</i> is in-memeory, and <i>test</i> is the database name). The <i>show_sq</i>l option, if set to true will display all the executed SQL queries on the console. The property <i>hbm2ddl.auto </i>, if set to <i>update</i>, will change the existing database schema on each start up. In the end we add the Person.hbm.xml and Address.hbm.xml files to the configuration.</p>
<p><b>Note</b> : In case you want to use any other database then, you need to change these properties -<br />
&#8220;dialect&#8221;, &#8220;connection.driver_class&#8221;, &#8220;connection.url&#8221;, &#8220;connection.username&#8221;, and &#8220;connection.password&#8221;</p>
<h2>6. Create Utility class</h2>
<p>Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file <b>src\main\java\net\javabeat\hibernate\HibernateUtil.java</b> as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = 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>7. Revise the App class</h2>
<p>Next we will revise the App.java (generated by Maven). This class tests the one-to-one relationship by creating and listing the person names and coressponding addresses as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Main class
 *
 */
public class App {
	public static void main(String[] args) {
		System.out.println(&quot;Maven + Hibernate + HSQL XML One to One Mapping &quot;);
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		App app = new App();

		Address address1 = new Address(&quot;M.G.Road&quot;, &quot;Bangalore&quot;, &quot;Karnataka&quot;,
				&quot;56000&quot;);
		Address address2 = new Address(&quot;Tilak Road&quot;, &quot;Pune&quot;, &quot;Maharashtra&quot;,
				&quot;411207&quot;);

		app.savePersonInfo(&quot;Jiya&quot;, address1);
		app.savePersonInfo(&quot;Manisha&quot;, address2);

		app.listPersonInfo();

	}

	public Long savePersonInfo(String personName, Address address) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Long personId = null;
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Person person = new Person();
			person.setName(personName);

			person.setAddress(address);
			address.setPerson(person);
			session.save(person);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return personId;
	}

	/*
	 * Lists the person's from database table
	 */
	public void listPersonInfo() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			@SuppressWarnings(&quot;unchecked&quot;)
			List&lt;Person&gt; personList = session.createQuery(&quot;from Person&quot;).list();
			for (Iterator&lt;Person&gt; iterator = personList.iterator(); iterator
					.hasNext();) {
				Person person = (Person) iterator.next();
				System.out.println(person.getName());
				System.out.println(person.getAddress().getStreet() + &quot; &quot;
						+ person.getAddress().getCity() + &quot; &quot;
						+ person.getAddress().getState() + &quot; &quot;
						+ person.getAddress().getZipcode());
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
</pre>
<p>Here the savePersonInfo() method is used to save a new Person object and Address object to the database. In the savePersonInfo() method a new object of the Person class is created and the name value and address is set. The personId value is auto generated so the value need not be set here. We then save the Person object to the Address object. The session.save() method is used to persist the value in the database and once the value is saved, the id value (Primary key) is returned. Once the object is saved, the transaction is committed. If any exception occurs then the transaction is rolledback. The transaction ends either through commit or rollback action. Once the transaction ends the session is closed.</p>
<p>The listPersonInfo() method is used to list name of each person in PERSON table and their corresponding addresses from ADDRESS table. Here we use Hibernate Query Language (HQL). The query <b>&#8220;from Person&#8221;</b> returns a list of all the data in the PERSON table and their corresponding addresses from ADDRESS table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Person and corresponding Address table and hence display them on the console.</p>
<h2>8. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_dir_struct.jpg"><img class="size-medium wp-image-6153 aligncenter" alt="onetoone_dir_struct" src="http://www.javabeat.net/wp-content/uploads/2013/03/onetoone_dir_struct-198x300.jpg" width="198" height="300" /></a></p>
<h2>9. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class.<br />
Right click on App.java &gt;Run As &gt; Java Application.<br />
On start of each thread, a database schema will be created and the following actions will happen.</p>
<p><b>Output on the console:</b><br />
Following output is displayed on the console:</p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + HSQL XML One to One Mapping
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        person
        (PERSON_ID, NAME)
    values
        (null, ?)
Hibernate:
    insert
    into
        address
        (ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIPCODE, PERSON_ID)
    values
        (?, ?, ?, ?, ?)
Hibernate:
    insert
    into
        person
        (PERSON_ID, NAME)
    values
        (null, ?)
Hibernate:
    insert
    into
        address
        (ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIPCODE, PERSON_ID)
    values
        (?, ?, ?, ?, ?)
Hibernate:
    select
        person0_.PERSON_ID as PERSON1_0_,
        person0_.NAME as NAME0_
    from
        person person0_
Hibernate:
    select
        address0_.PERSON_ID as PERSON1_1_0_,
        address0_.ADDRESS_STREET as ADDRESS2_1_0_,
        address0_.ADDRESS_CITY as ADDRESS3_1_0_,
        address0_.ADDRESS_STATE as ADDRESS4_1_0_,
        address0_.ADDRESS_ZIPCODE as ADDRESS5_1_0_
    from
        address address0_
    where
        address0_.PERSON_ID=?
Hibernate:
    select
        address0_.PERSON_ID as PERSON1_1_0_,
        address0_.ADDRESS_STREET as ADDRESS2_1_0_,
        address0_.ADDRESS_CITY as ADDRESS3_1_0_,
        address0_.ADDRESS_STATE as ADDRESS4_1_0_,
        address0_.ADDRESS_ZIPCODE as ADDRESS5_1_0_
    from
        address address0_
    where
        address0_.PERSON_ID=?
Jiya
M.G.Road Bangalore Karnataka 56000
Manisha
Tilak Road Pune Maharashtra 411207

</pre>
<h2>Summary</h2>
<ul>
<li><a class="downloadlink" href="http://www.javabeat.net/downloads/20130319-HibernateOneToOneXML.zip" title=" downloaded 6 times" >Source Code Download for HibernateOneToOneXML (6)</a></li>
</ul>
<p>In this post we first created a simple Java project using Maven and made it compatible with eclipse. Then we added the Hibernate one to one relation by creating two hibernate XML files Person and Address and relating them uing the <b>one-to-one</b> tag in both the files. We used a simple HSQL database, to insert records into Person and Address table and also listed these records. In the next article we shall look into Hibernate One-To-One Mapping using Java Annotations. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-one-to-one-mapping/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate, Maven and HSQL – Example Project (Using Annotations)</title>
		<link>http://www.javabeat.net/2013/03/hibernate-maven-and-hsql-annotations/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-maven-and-hsql-annotations/#comments</comments>
		<pubDate>Mon, 11 Mar 2013 14:28:21 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[MYSQL]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6131</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate, HSQL and Maven using Java 5 Annotations. For this we will use our previous example in the post Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping)) as base and convert it from XML Mapping to Annotation. HSQL database is used to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate, HSQL and Maven</strong></span> using Java 5 Annotations. For this we will use our previous example in the post <a title="Hibernate, Maven and HSQL - Example Project(XML Mapping)" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping))</a> as base and convert it from XML Mapping to Annotation.<br />
HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a>.</p>
<p>Following are the tools and technologies required for this project:</p>
<ul>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (Download from <a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">http://hibernate.org/downloads</a>)</li>
<li>HsqlDB (Download from <a href="http://hsqldb.org/" target="_blank">http://hsqldb.org/</a>)</li>
</ol>
</ul>
<h2>1. Generating Maven Java project compatible with Eclipse</h2>
<p>Follow the steps in the post <a title="Hibernate, Maven and HSQL - Example Project(XML Mapping)" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping))</a> to create project structure. Or you can directly download the source code from above post in Eclipse and rename the project in eclipse as <b>HibernateHelloWorldAnnotation</b>.</p>
<h2>2.Updating the Hibernate dependency in pom.xml</h2>
<p>As we are going to use Annotation mapping in Hibernate we will update our existing pom.xml file as below:</p>
<pre class="brush: java; 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.javabeat.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;junit&lt;/groupId&gt;
     &lt;artifactId&gt;junit&lt;/artifactId&gt;
     &lt;version&gt;3.8.1&lt;/version&gt;
     &lt;scope&gt;test&lt;/scope&gt;
   &lt;/dependency&gt;
&lt;!-- Hibernate library dependecy start --&gt;
 &lt;b&gt; &lt;dependency&gt;
     &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
     &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;
     &lt;version&gt;4.1.9.Final&lt;/version&gt;
  &lt;/dependency&gt;&lt;/b&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;org.hsqldb&lt;/groupId&gt;
     &lt;artifactId&gt;hsqldb&lt;/artifactId&gt;
     &lt;version&gt;2.2.9&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-logging&lt;/groupId&gt;
     &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
     &lt;version&gt;1.1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-collections&lt;/groupId&gt;
     &lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
     &lt;version&gt;3.2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;cglib&lt;/groupId&gt;
     &lt;artifactId&gt;cglib&lt;/artifactId&gt;
     &lt;version&gt;2.2&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;asm&lt;/groupId&gt;
     &lt;artifactId&gt;asm&lt;/artifactId&gt;
     &lt;version&gt;4.0&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;ehcache&lt;/groupId&gt;
      &lt;artifactId&gt;ehcache&lt;/artifactId&gt;
      &lt;version&gt;1.2.3&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
      &lt;version&gt;3.2.3.GA&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;jta&lt;/groupId&gt;
      &lt;artifactId&gt;jta&lt;/artifactId&gt;
      &lt;version&gt;1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;log4j&lt;/groupId&gt;
      &lt;artifactId&gt;log4j&lt;/artifactId&gt;
      &lt;version&gt;1.2.11&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;oscache&lt;/groupId&gt;
      &lt;artifactId&gt;oscache&lt;/artifactId&gt;
      &lt;version&gt;2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;persistence-api&lt;/groupId&gt;
      &lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
      &lt;version&gt;1.0&lt;/version&gt;
   &lt;/dependency&gt;
  &lt;!-- Hibernate library dependency end --&gt;
&lt;/dependencies&gt;
&lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and update eclipse classpath. Go to the directory of the project (in our case it is C:\HibernateHelloWorldXML) and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<p>This step is optional. If your Eclipse has Maven plugin installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by following these instructions : Right click on project &gt; Maven &gt; Enable Dependency Management.</p>
<h2>3. Delete the unused Hibernate Mapping file</h2>
<p>The file src\main\resources\net\javabeat\hibernate\Contact.hbm.xml is not required anymore. Delete this file from the project.</p>
<h2>4. Update the Model class file</h2>
<p>We will add simple annotations to the model class (<em>src\main\java\net\javabeat\hibernate\Contact.java</em>) as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Model class for Conact
 */
@Entity
@Table(name=&quot;CONTACT&quot;)
public class Contact implements Serializable {
   @Id
   @GeneratedValue
   private Integer contactId;

   @Column(name=&quot;name&quot;)
   private String name;

   public Contact() {
   }

   public Integer getContactId() {
      return contactId;
   }

   public void setContactId(Integer contactId) {
      this.contactId = contactId;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

}
</pre>
<h2>5.Update the Hibernate Utility class</h2>
<p>In our previous post for XML mapping, we were using Configuration class to generate SessionFactory object. In HibernateUtil we had following line of code:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
sessionFactory = new Configuration().configure().buildSessionFactory();
</pre>
<p>We will update this and use AnnotationConfiguration instead of Configuration(). The updated HibernateUtil.java file is as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
   private static final SessionFactory sessionFactory;
   static {
      try {
	   sessionFactory = 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. Update Hibernate Configuration file</h2>
<p>The configuration file hibernate.cfg.xml, needs to be changed to add the new Annotation based entity class Contact.java instead of old XML Mapping Contact.hbm.xml. The updated src\main\resources\hibernate.cfg.xml is as below:</p>
<pre class="brush: java; 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;?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, Connect to HSQL, IN Memory  --&gt;
    &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.HSQLDialect&lt;/property&gt;
    &lt;property name=&quot;connection.driver_class&quot;&gt;org.hsqldb.jdbcDriver&lt;/property&gt;
    &lt;property name=&quot;connection.url&quot;&gt;jdbc:hsqldb:mem:test&lt;/property&gt;
    &lt;property name=&quot;connection.username&quot;&gt;sa&lt;/property&gt;
    &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

     &lt;!-- JDBC connection pool (use the built-in) --&gt;
     &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
     &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;&lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;
     &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
     &lt;!--create the database schema on startup if required --&gt;
     &lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;
     &lt;mapping class=&quot;net.javabeat.hibernate.Contact&quot;&gt;&lt;/mapping&gt;
  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>Here we have replaced</p>
<pre class="brush: java; title: ; notranslate">
&lt;mapping resource=&quot;net/javabeat/hibernate/Contact.hbm.xml&quot;&gt;&lt;/mapping&gt;
</pre>
<p>with</p>
<pre class="brush: java; title: ; notranslate">
 &lt;mapping class=&quot;net.javabeat.hibernate.Contact&quot;&gt;&lt;/mapping&gt;
</pre>
<h2>7. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/final_proj_stuct_annotation.jpg"><img class="size-medium wp-image-6133 aligncenter" alt="final_proj_stuct_annotation" src="http://www.javabeat.net/wp-content/uploads/2013/03/final_proj_stuct_annotation-160x300.jpg" width="160" height="300" /></a></p>
<h2>8. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class.<br />
Right click on App.java &gt;Run As &gt; Java Application.<br />
On start of each thread, a database schema will be created and the following actions will happen.</p>
<ul>
<ul>
<li>Each time a new thread starts the database schema will change the existing one as we have set <i>hbm2ddl.auto option to update</i>.</li>
<li>The SQL statement generated gets displayed on the console. This is set using the show_sql option in the hibernate configuration file.</li>
</ul>
</ul>
<p><b>Output on the console:</b></p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + HSQL
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    select
        contact0_.contactId as contactId0_,
        contact0_.name as name0_
    from
        CONTACT contact0_
Jiya
Manisha
Riya
</pre>
<h2>Summary</h2>
<p>In this post we updated our previous Java project from post <a title="Hibernate, Maven and HSQL - Example Project(XML Mapping)" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping))</a> using Maven and made it compatible with eclipse. Then we updated the Hibernate configuration file and also deleted the hibernate mapping file. We also updated our Model class with Java annotations. We used a simple HSQL database, to insert records into CONTACT table and also listed these records. In the next article we shall look into Hibernate Association (One-to-one mapping(XML mapping)). If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-maven-and-hsql-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping)</title>
		<link>http://www.javabeat.net/2013/03/hibernate-maven-hsql/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-maven-hsql/#comments</comments>
		<pubDate>Sat, 02 Mar 2013 06:12:30 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6033</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate, HSQL and Maven. We will first create a Java project using Maven and then will add Hibernate on it. HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline"><strong>Hibernate, HSQL and Maven</strong></span>. We will first create a Java project using Maven and then will add Hibernate on it. HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a>.</p>
<p>Following are the tools and technologies required for this project:</p>
<ul>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (Download from <a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">http://hibernate.org/downloads</a>)</li>
<li>HsqlDB (Download from <a href="http://hsqldb.org/" target="_blank">http://hsqldb.org/</a>)</li>
</ol>
</ul>
<ul>
<li><strong>Download Source Code:</strong> <a class="downloadlink" href="http://www.javabeat.net/downloads/2013-03-hibernate-maven-hsql.zip" title=" downloaded 28 times" >Hibernate, Maven and HSQL - Example (28)</a></li>
</ul>
<h2>1. Generating Maven Java project compatible with Eclipse</h2>
<p>We will create a Java project using Maven (Refer post <a title="Creating Simple Java Project Using Apache Maven" href="http://www.javabeat.net/2013/02/creating-simple-java-project-using-apache-maven/" target="_blank">Creating Simple Java Project Using Apache Maven</a>). Open the command line window and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateHelloWorldXML
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
</pre>
<p>On execution of the above command, a java project <b>HibernateHelloWorldXML</b> is created (In our case we have created it in the directory C:\HibernateProject). This java project already has a directory structure (as explained in the post (Refer post <a title="Creating Simple Java Project Using Apache Maven" href="http://www.javabeat.net/2013/02/creating-simple-java-project-using-apache-maven/" target="_blank">Creating Simple Java Project Using Apache Maven</a>)). To make this project compatible with eclipse, let&#8217;s execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<p>The goal <i>eclipse:eclipse</i> generates the following eclipse configuration files:</p>
<ul>
<li><i>.project</i> and <i>.classpath</i> files.</li>
<li><i>.setting/org.eclipse.jdt.core.prefs</i> with project specific compiler settings.</li>
<li>Various configuration files for WTP (Web Tools Project), if the parameter wtpversion is set to a valid version (WTP configuration is not generated by default).</li>
</ul>
<h2>2. Import project into Eclipse</h2>
<p>Open Eclipse and import the above Java project as explained below:</p>
<p><b>File &gt; Import&#8230; &gt; General &gt; Existing Projects into Workspace &gt; Choose above Java project</b></p>
<p>Once the project is imported the directory structure would be as in the screen below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/dir_struct_eclipse.jpg"><img class="size-medium wp-image-6038 aligncenter" alt="dir_struct_eclipse" src="http://www.javabeat.net/wp-content/uploads/2013/03/dir_struct_eclipse-203x300.jpg" width="203" height="300" /></a></p>
<p><b>Build-path settings</b><br />
Goto Window &gt; Preferences&#8230; &gt; Java &gt; Build Path &gt; Classpath Variables &gt;</p>
<ul>
<li>Define new variable M2_REPO pointing to your local maven repository. (In our case it is:C:/Documents and Settings/Manisha/.m2/repository).</li>
<li>Define new variable HSQLDB pointing to the hsqldb.jar. (C:/tools/hsqldb-2.2.9/hsqldb/lib/hsqldb.jar).</li>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/03/classpath_setting.jpg"><img class="size-medium wp-image-6039 aligncenter" alt="classpath_setting" src="http://www.javabeat.net/wp-content/uploads/2013/03/classpath_setting-300x145.jpg" width="300" height="145" /></a></p>
<h2>3. Adding the Hibernate and HSQLDB Dependency to pom.xml</h2>
<p>We need to add the Hibernate, <strong>HSQLDB</strong> and some other dependencies to the Maven pom.xml as shown below:</p>
<pre class="brush: java; 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.javabeat.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;junit&lt;/groupId&gt;
     &lt;artifactId&gt;junit&lt;/artifactId&gt;
     &lt;version&gt;3.8.1&lt;/version&gt;
     &lt;scope&gt;test&lt;/scope&gt;
   &lt;/dependency&gt;
&lt;!-- Hibernate library dependecy start --&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
     &lt;artifactId&gt;hibernate&lt;/artifactId&gt;
     &lt;version&gt;4.1.9.Final&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;org.hsqldb&lt;/groupId&gt;
     &lt;artifactId&gt;hsqldb&lt;/artifactId&gt;
     &lt;version&gt;2.2.9&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;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-logging&lt;/groupId&gt;
     &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
     &lt;version&gt;1.1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-collections&lt;/groupId&gt;
     &lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
     &lt;version&gt;3.2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;cglib&lt;/groupId&gt;
     &lt;artifactId&gt;cglib&lt;/artifactId&gt;
     &lt;version&gt;2.2&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;asm&lt;/groupId&gt;
     &lt;artifactId&gt;asm&lt;/artifactId&gt;
     &lt;version&gt;4.0&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;ehcache&lt;/groupId&gt;
      &lt;artifactId&gt;ehcache&lt;/artifactId&gt;
      &lt;version&gt;1.2.3&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
      &lt;version&gt;3.2.3.GA&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;jta&lt;/groupId&gt;
      &lt;artifactId&gt;jta&lt;/artifactId&gt;
      &lt;version&gt;1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;log4j&lt;/groupId&gt;
      &lt;artifactId&gt;log4j&lt;/artifactId&gt;
      &lt;version&gt;1.2.11&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;oscache&lt;/groupId&gt;
      &lt;artifactId&gt;oscache&lt;/artifactId&gt;
      &lt;version&gt;2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;persistence-api&lt;/groupId&gt;
      &lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
      &lt;version&gt;1.0&lt;/version&gt;
   &lt;/dependency&gt;
  &lt;!-- Hibernate library dependecy end --&gt;
&lt;/dependencies&gt;
&lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath.</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<p>This step is optional. If your Eclipse has Maven plugin installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by following these instructions : Right click on project &gt; Maven &gt; Enable Dependency Management.</p>
<h2>4. Create Model Class and Hibernate Mapping file</h2>
<p>As a next step let&#8217;s create the model class (<em>src\main\java\net\javabeat\hibernate\Contact.java</em>) as below:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;
import java.io.Serializable;
/**
   * Model class for Contact
*/
public class Contact implements Serializable {
   private Integer contactId;
   private String name;

   public Contact() {
    }

   public Integer getContactId() {
      return contactId;
   }

   public void setContactId(Integer contactId) {
       this.contactId = contactId;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

}
</pre>
<p>Next let&#8217;s write a Hibernate XML Mapping file to the directory:<b>/src/main/resources </b>. Create the <i>resources</i> directory as follows: Right click on Project &gt; New &gt; Source Folder &gt; Give folder name &#8220;/src/main/resources/&#8221; and click Finish. Write the file <b>src\main\resources\net\javabeat\hibernate\Contact.hbm.xml</b> for the Model class as below:</p>
<pre class="brush: java; title: ; notranslate">
 &lt;?xml version=&quot;1.0&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&gt;
    &lt;class name=&quot;net.javabeat.hibernate.Contact&quot; table=&quot;contact&quot;&gt;
         &lt;id name=&quot;contactId&quot; type=&quot;java.lang.Integer&quot;&gt;
             &lt;column name=&quot;CONTACT_ID&quot; /&gt;
             &lt;generator class=&quot;identity&quot; /&gt;
         &lt;/id&gt;
         &lt;property name=&quot;name&quot; type=&quot;string&quot;&gt;
             &lt;column name=&quot;NAME&quot; length=&quot;10&quot; not-null=&quot;true&quot; unique=&quot;true&quot; /&gt;
         &lt;/property&gt;
       &lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<p>The details of the above file are as below:</p>
<ul>
<li>The <i>hibernate-mapping</i> element is the root element.</li>
<li>The <i>class</i> element is used to map the Java class with the database table.</li>
<li>The Java class name is specified using the <i>name</i> attribute of the class element</li>
<li>The database table name is specified using the <i>table</i> attribute of the class element.</li>
<li>The <i>id</i> element is used to create the primary key.</li>
<li>The <i>name</i> attribute of the <i>id</i> element refers to the property in the Contact class and the <i>column</i> attribute refers to the column in the CONTACT table.</li>
<li>The <i>type</i> attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type and vice versa.</li>
<li>The <i>generator</i> element within the id element is used to automatically generate the primary key values.</li>
<li>The property element is used to link a property in the Java class to a column in the database table.</li>
</ul>
<h2>5. Adding Hibernate Configuration file</h2>
<p>As a next step let&#8217;s add the hibernate.cfg.xml to the directory:<b>/src/main/resources </b>. Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:</p>
<pre class="brush: java; 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;?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, Connect to HSQL, IN Memory  --&gt;
    &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.HSQLDialect&lt;/property&gt;
    &lt;property name=&quot;connection.driver_class&quot;&gt;org.hsqldb.jdbcDriver&lt;/property&gt;
    &lt;property name=&quot;connection.url&quot;&gt;jdbc:hsqldb:mem:test&lt;/property&gt;
    &lt;property name=&quot;connection.username&quot;&gt;sa&lt;/property&gt;
    &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

     &lt;!-- JDBC connection pool (use the built-in) --&gt;
     &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
     &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;&lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;
     &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
     &lt;!--create the database schema on startup if required --&gt;
     &lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;
     &lt;mapping resource=&quot;net/javabeat/hibernate/Contact.hbm.xml&quot;&gt;&lt;/mapping&gt;
  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>In the above file we have set the database connection to HSQL-In memory database (<i>mem</i> is in-memeory, and <i>test</i> is the database name). The <i>show_sq</i>l option, if set to true will display all the executed SQL queries on the console. The property <i>hbm2ddl.auto </i>, if set to <i>update</i>, will change the existing database schema on each startup. In the end we add the Contact.hbm.xml file to the configuration.</p>
<p><b>Note</b> : In case you want to use any other database then, you need to change these properties -<br />
&#8220;dialect&#8221;, &#8220;connection.driver_class&#8221;, &#8220;connection.url&#8221;, &#8220;connection.username&#8221;, and &#8220;connection.password&#8221;</p>
<h2>6. Create Utility class</h2>
<p>Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file <b>src\main\java\net\javabeat\hibernate\HibernateUtil.java</b> as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = 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>7. Revise the App class</h2>
<p>Next we will revise the App.java (generated by Maven), to create and list the contact names as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class App {
  public static void main(String[] args) {
     System.out.println(&quot;Maven + Hibernate + HSQL&quot;);
     Session session = HibernateUtil.getSessionFactory().openSession();
     session.beginTransaction();
     App app = new App();
     app.saveContact(&quot;Jiya&quot;);
     app.saveContact(&quot;Manisha&quot;);
     app.saveContact(&quot;Riya&quot;);
     app.listContact();
   }

   public Integer saveContact(String contactName) {
      Session session = HibernateUtil.getSessionFactory().openSession();
      session.beginTransaction();
      Integer contactId = null;
      Transaction transaction = null;
      try {
           transaction = session.beginTransaction();
           Contact contact = new Contact();
           contact.setName(contactName);
           contactId = (Integer) session.save(contact);
           transaction.commit();
       } catch (HibernateException e) {
           transaction.rollback();
           e.printStackTrace();
       } finally {
           session.close();
       }
       return contactId;
   }

   public void listContact() {
       Session session = HibernateUtil.getSessionFactory().openSession();
       Transaction transaction = null;
       try {
           transaction = session.beginTransaction();
           @SuppressWarnings(&quot;unchecked&quot;)
           List&lt;Contact&gt; contactList = session.createQuery(&quot;from Contact&quot;)
               .list();
           for (Iterator&lt;Contact&gt; iterator = contactList.iterator(); iterator
                   .hasNext();) {
               Contact contact = (Contact) iterator.next();
               System.out.println(contact.getName());
           }
           transaction.commit();
       } catch (HibernateException e) {
           transaction.rollback();
           e.printStackTrace();
       } finally {
           session.close();
       }
   }

}
</pre>
<p>Here the saveContact() method is used to save a new Contact object to the database. In the saveContact() method a new object of the Contact class is created and the contactName value is set, the contactId value is auto generated so the value need not be set here. The session.save() method is used to persist the value in the database and once the value is saved, the id value (Primary key) is returned. Here the contactId value is of type Integer so we typecast the returned value to Integer. Once the object is saved, the transaction is committed. If any exception occurs then the transaction is rolledback. The transaction ends either through commit or rollback action. Once the transaction ends the session is closed.</p>
<p>The listContact() method is used to list all the contacts. The session.createQuery() method is used to create a query object which helps in retrieving the persistant objects. Here we use Hibernate Query Language (HQL). &#8220;from Contact&#8221; returns a list of all the contacts in the CONTACT table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list of contacts and display them on the console.</p>
<h2>8. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/final_proj_stuct.jpg"><img class="size-medium wp-image-6044 aligncenter" alt="final_proj_stuct" src="http://www.javabeat.net/wp-content/uploads/2013/03/final_proj_stuct-140x300.jpg" width="140" height="300" /></a></p>
<h2>9. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class.<br />
Right click on App.java &gt;Run As &gt; Java Application.<br />
On start of each thread, a database schema will be created and the following actions will happen.</p>
<ul>
<ul>
<li>Each time a new thread starts the database schema will change the existing one as we have set <i>hbm2ddl.auto option to update</i>.</li>
<li>The SQL statement generated gets displayed on the console. This is set using the show_sql option in the hibernate configuration file.</li>
</ul>
</ul>
<p><b>Output on the console:</b><br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/console.jpg"><img class="size-medium wp-image-6046 aligncenter" alt="console" src="http://www.javabeat.net/wp-content/uploads/2013/03/console-300x271.jpg" width="300" height="271" /></a></p>
<h2>Summary</h2>
<ul>
<li><strong>Download Source Code:</strong> <a class="downloadlink" href="http://www.javabeat.net/downloads/2013-03-hibernate-maven-hsql.zip" title=" downloaded 28 times" >Hibernate, Maven and HSQL - Example (28)</a></li>
</ul>
<p>In this post we first created a simple Java project using Maven and made it compatible with eclipse. Then we added the Hibernate XML mapping to this project. We used a simple HSQL database, to insert records into CONTACT table and also listed these records. In the next article we shall look into creating hibernate project using Java Annotations. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-maven-hsql/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Hibernate XML configuration file example</title>
		<link>http://www.javabeat.net/2013/02/hibernate-xml-configuration-file-example/</link>
		<comments>http://www.javabeat.net/2013/02/hibernate-xml-configuration-file-example/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 04:21:51 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5938</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p></p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><pre class="brush: java; title: ; notranslate">
&lt;pre&gt;&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
    &quot;-//Hibernate/Hibernate Configuration DTD//EN&quot;
    &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;

    &lt;!-- a SessionFactory instance listed as /jndi/name --&gt;
    &lt;session-factory
        name=&quot;java:hibernate/SessionFactory&quot;&gt;

        &lt;!-- properties --&gt;
        &lt;property name=&quot;connection.datasource&quot;&gt;java:/comp/env/jdbc/MyDB&lt;/property&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;false&lt;/property&gt;
        &lt;property name=&quot;transaction.factory_class&quot;&gt;
            org.hibernate.transaction.JTATransactionFactory
        &lt;/property&gt;
        &lt;property name=&quot;jta.UserTransaction&quot;&gt;java:comp/UserTransaction&lt;/property&gt;

        &lt;!-- mapping files --&gt;
        &lt;mapping resource=&quot;org/hibernate/auction/Item.hbm.xml&quot;/&gt;
        &lt;mapping resource=&quot;org/hibernate/auction/Bid.hbm.xml&quot;/&gt;

        &lt;!-- cache settings --&gt;
        &lt;class-cache usage=&quot;read-write&quot;/&gt;
        &lt;class-cache usage=&quot;read-only&quot;/&gt;
        &lt;collection-cache collection=&quot;org.hibernate.auction.Item.bids&quot; usage=&quot;read-write&quot;/&gt;

    &lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;&lt;/pre&gt;
</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/hibernate-xml-configuration-file-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>List of Hibernate SQL Dialects</title>
		<link>http://www.javabeat.net/2013/02/list-of-hibernate-sql-dialects/</link>
		<comments>http://www.javabeat.net/2013/02/list-of-hibernate-sql-dialects/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 03:40:56 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5922</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>RDBMS Dialect DB2 org.hibernate.dialect.DB2Dialect DB2 AS/400 org.hibernate.dialect.DB2400Dialect DB2 OS390 org.hibernate.dialect.DB2390Dialect PostgreSQL org.hibernate.dialect.PostgreSQLDialect MySQL org.hibernate.dialect.MySQLDialect MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect Oracle (any version) org.hibernate.dialect.OracleDialect Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect Sybase org.hibernate.dialect.SybaseDialect Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect Microsoft SQL Server org.hibernate.dialect.SQLServerDialect SAP DB org.hibernate.dialect.SAPDBDialect Informix org.hibernate.dialect.InformixDialect HypersonicSQL org.hibernate.dialect.HSQLDialect Ingres org.hibernate.dialect.IngresDialect Progress org.hibernate.dialect.ProgressDialect Mckoi SQL org.hibernate.dialect.MckoiDialect Interbase org.hibernate.dialect.InterbaseDialect Pointbase [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><table summary="Hibernate SQL Dialects (hibernate.dialect)" border="1">
<thead>
<tr>
<th>RDBMS</th>
<th>Dialect</th>
</tr>
</thead>
<tbody>
<tr>
<td>DB2</td>
<td><tt>org.hibernate.dialect.DB2Dialect</tt></td>
</tr>
<tr>
<td>DB2 AS/400</td>
<td><tt>org.hibernate.dialect.DB2400Dialect</tt></td>
</tr>
<tr>
<td>DB2 OS390</td>
<td><tt>org.hibernate.dialect.DB2390Dialect</tt></td>
</tr>
<tr>
<td>PostgreSQL</td>
<td><tt>org.hibernate.dialect.PostgreSQLDialect</tt></td>
</tr>
<tr>
<td>MySQL</td>
<td><tt>org.hibernate.dialect.MySQLDialect</tt></td>
</tr>
<tr>
<td>MySQL with InnoDB</td>
<td><tt>org.hibernate.dialect.MySQLInnoDBDialect</tt></td>
</tr>
<tr>
<td>MySQL with MyISAM</td>
<td><tt>org.hibernate.dialect.MySQLMyISAMDialect</tt></td>
</tr>
<tr>
<td>Oracle (any version)</td>
<td><tt>org.hibernate.dialect.OracleDialect</tt></td>
</tr>
<tr>
<td>Oracle 9i/10g</td>
<td><tt>org.hibernate.dialect.Oracle9Dialect</tt></td>
</tr>
<tr>
<td>Sybase</td>
<td><tt>org.hibernate.dialect.SybaseDialect</tt></td>
</tr>
<tr>
<td>Sybase Anywhere</td>
<td><tt>org.hibernate.dialect.SybaseAnywhereDialect</tt></td>
</tr>
<tr>
<td>Microsoft SQL Server</td>
<td><tt>org.hibernate.dialect.SQLServerDialect</tt></td>
</tr>
<tr>
<td>SAP DB</td>
<td><tt>org.hibernate.dialect.SAPDBDialect</tt></td>
</tr>
<tr>
<td>Informix</td>
<td><tt>org.hibernate.dialect.InformixDialect</tt></td>
</tr>
<tr>
<td>HypersonicSQL</td>
<td><tt>org.hibernate.dialect.HSQLDialect</tt></td>
</tr>
<tr>
<td>Ingres</td>
<td><tt>org.hibernate.dialect.IngresDialect</tt></td>
</tr>
<tr>
<td>Progress</td>
<td><tt>org.hibernate.dialect.ProgressDialect</tt></td>
</tr>
<tr>
<td>Mckoi SQL</td>
<td><tt>org.hibernate.dialect.MckoiDialect</tt></td>
</tr>
<tr>
<td>Interbase</td>
<td><tt>org.hibernate.dialect.InterbaseDialect</tt></td>
</tr>
<tr>
<td>Pointbase</td>
<td><tt>org.hibernate.dialect.PointbaseDialect</tt></td>
</tr>
<tr>
<td>FrontBase</td>
<td><tt>org.hibernate.dialect.FrontbaseDialect</tt></td>
</tr>
<tr>
<td>Firebird</td>
<td><tt>org.hibernate.dialect.FirebirdDialect</tt></td>
</tr>
</tbody>
</table>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/list-of-hibernate-sql-dialects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
