<?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>Java Bulgaria &#187; Hibernate</title>
	<atom:link href="http://javabg.eu/category/hibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://javabg.eu</link>
	<description>Всичко за Java</description>
	<lastBuildDate>Tue, 24 Jan 2012 16:46:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Hibernate – Many-to-many relationship  example</title>
		<link>http://javabg.eu/2010/02/hibernate-%e2%80%93-many-to-many-relationship-example/</link>
		<comments>http://javabg.eu/2010/02/hibernate-%e2%80%93-many-to-many-relationship-example/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 09:43:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[английски]]></category>
		<category><![CDATA[уроци]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=431</guid>
		<description><![CDATA[“Many-to-many” example This is a many-to-many relationship table design, a STOCK table has more than one CATEGORY, and CATEGORY can belong to more than one STOCK, the relationship is linked with a third table called STOCK_CATEGORY. Hibernate implementation In Hibernate, this “many-to-many” relationship can implemented in two ways : Hibernate XML Mapping file Hibernate Annotation [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<h3>“Many-to-many” example</h3>
<p>This is a <strong>many-to-many</strong> relationship <span id="IL_AD1">table design</span>, a <span id="IL_AD3">STOCK</span> table has more than one CATEGORY, and CATEGORY  can belong to more than one STOCK, the relationship is linked with a  third table called STOCK_CATEGORY.</p>
<div><img title="many-to-many-relationship" src="http://www.mkyong.com/wp-content/uploads/2010/01/many-to-many-relationship.jpg" alt="many-to-many-relationship" width="341" height="116" /></div>
<h3>Hibernate implementation</h3>
<p>In Hibernate, this “many-to-many” relationship can implemented in two  ways :</p>
<ul>
<li>Hibernate XML Mapping file</li>
<li>Hibernate Annotation</li>
</ul>
<h4>1. Hibernate XML mapping file</h4>
<p>In XML mapping way, you need three Java <span id="IL_AD7">classes</span> to hold the table data,</p>
<ul>
<li>Stock.java -&gt; STOCK table</li>
<li>Category.java -&gt; CATEGORY table</li>
<li>StockCategory.java -&gt; STOCK_CATEGORY table</li>
</ul>
<p>and three XML mapping files to describe the table relationship.</p>
<ul>
<li>Stock.hbm.xml -&gt; STOCK table</li>
<li>Category.hbm.xml -&gt; CATEGORY table</li>
<li>StockCategory.hbm.xml -&gt; STOCK_CATEGORY table</li>
</ul>
<h5>Stock.java</h5>
<div>
<div>
<pre style="font-family: monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Stock <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
   <span style="color: #000000; font-weight: bold;"><span id="IL_AD6">private</span></span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
   ...
   <span style="color: #000000; font-weight: bold;">public</span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> getStockCategories<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">}</span>

   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStockCategories<span style="color: #009900;">(</span>Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span> <span style="color: #339933;">=</span> stockCategories<span style="color: #339933;">;</span>
   <span style="color: #009900;">}</span></pre>
</div>
</div>
<h5>Category.java</h5>
<div>
<div>
<pre style="font-family: monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Category <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
   <span style="color: #000000; font-weight: bold;">private</span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
   ...
   <span style="color: #000000; font-weight: bold;">public</span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> getStockCategories<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">}</span>

   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStockCategories<span style="color: #009900;">(</span>Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span> <span style="color: #339933;">=</span> stockCategories<span style="color: #339933;">;</span>
   <span style="color: #009900;">}</span></pre>
</div>
</div>
<h5>StockCategory.java</h5>
<div>
<div>
<pre style="font-family: monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StockCategory <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> stockCategoryId<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> Stock stock<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> Category category<span style="color: #339933;">;</span>
   ...</pre>
</div>
</div>
<h5>Stock.hbm.xml</h5>
<div>
<div>
<pre style="font-family: monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"com.mkyong.common.Stock"</span> <span style="color: #000066;">table</span>=<span style="color: #ff0000;">"stock"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stockId"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"java.lang.<span id="IL_AD8">Integer</span>"</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"STOCK_ID"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;generator</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"identity"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   ...
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;set</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stockCategories"</span> <span style="color: #000066;">inverse</span>=<span style="color: #ff0000;">"true"</span> <span style="color: #000066;">lazy</span>=<span style="color: #ff0000;">"true"</span> </span>
<span style="color: #009900;">       <span style="color: #000066;">table</span>=<span style="color: #ff0000;">"stock_category"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"STOCK_ID"</span> <span style="color: #000066;">not-null</span>=<span style="color: #ff0000;">"true"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;one-to-many</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"com.mkyong.common.StockCategory"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/set<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre>
</div>
</div>
<p>Set inverse=”true” in set variable, Stock does not want to maintain  the relationship.</p>
<h5>Category.hbm.xml</h5>
<div>
<div>
<pre style="font-family: monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"com.mkyong.common.Category"</span> <span style="color: #000066;">table</span>=<span style="color: #ff0000;">"category"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"categoryId"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"java.lang.Integer"</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"CATEGORY_ID"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;generator</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"identity"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   ...
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;set</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stockCategories"</span> <span style="color: #000066;">inverse</span>=<span style="color: #ff0000;">"true"</span> <span style="color: #000066;">lazy</span>=<span style="color: #ff0000;">"true"</span> </span>
<span style="color: #009900;">       <span style="color: #000066;">table</span>=<span style="color: #ff0000;">"stock_category"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"CATEGORY_ID"</span> <span style="color: #000066;">not-null</span>=<span style="color: #ff0000;">"true"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;one-to-many</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"com.mkyong.common.StockCategory"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/set<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre>
</div>
</div>
<p>Set inverse=”true” in set variable, Category does not want to  maintain the relationship also.</p>
<h5>StockCategory.hbm.xml</h5>
<div>
<div>
<pre style="font-family: monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"com.mkyong.common.StockCategory"</span> <span style="color: #000066;">table</span>=<span style="color: #ff0000;">"stock_category"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stockCategoryId"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"java.lang.Integer"</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"STOCK_CATEGORY_ID"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;generator</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"identity"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;many-to-one</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stock"</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"com.mkyong.common.Stock"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"STOCK_ID"</span> <span style="color: #000066;">not-null</span>=<span style="color: #ff0000;">"true"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/many-to-one<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;many-to-one</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"category"</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"com.mkyong.common.Category"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"CATEGORY_ID"</span> <span style="color: #000066;">not-null</span>=<span style="color: #ff0000;">"true"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/many-to-one<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre>
</div>
</div>
<p>StockCategory maintain the relationship between Stock and Category,  see inverse=”true” explanation.</p>
<h4>2. Hibernate annotation</h4>
<p>In annotation way, three classes are required, all the relationships  are declared inside the Java classes.</p>
<ul>
<li>Stock.java -&gt; STOCK table</li>
<li>category.java -&gt; CATEGORY table</li>
<li>StockCategory.java -&gt; STOCK_CATEGORY table</li>
</ul>
<h5>Stock.java</h5>
<div>
<div>
<pre style="font-family: monospace;">...
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span>, catalog <span style="color: #339933;">=</span> <span style="color: #0000ff;">"mkyong"</span>, uniqueConstraints <span style="color: #339933;">=</span> <span style="color: #009900;">{</span>
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_NAME"</span><span style="color: #009900;">)</span>,
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_CODE"</span><span style="color: #009900;">)</span> <span style="color: #009900;">}</span><span style="color: #009900;">)</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Stock <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">private</span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories <span style="color: #339933;">=</span>
                                         <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
	...
	@Id
	@GeneratedValue<span style="color: #009900;">(</span>strategy <span style="color: #339933;">=</span> IDENTITY<span style="color: #009900;">)</span>
	@Column<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_ID"</span>, unique <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> getStockId<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockId</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>
        ...
	@OneToMany<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span>, mappedBy <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> getStockCategories<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>

	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStockCategories<span style="color: #009900;">(</span>Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span> <span style="color: #339933;">=</span> stockCategories<span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>
...</pre>
</div>
</div>
<h5>Category.java</h5>
<div>
<div>
<pre style="font-family: monospace;">...
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"category"</span>, catalog <span style="color: #339933;">=</span> <span style="color: #0000ff;">"mkyong"</span><span style="color: #009900;">)</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Category <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">private</span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories <span style="color: #339933;">=</span>
                                       <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        ...
	@Id
	@GeneratedValue<span style="color: #009900;">(</span>strategy <span style="color: #339933;">=</span> IDENTITY<span style="color: #009900;">)</span>
	@Column<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"CATEGORY_ID"</span>, unique <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> getCategoryId<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">categoryId</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>
	...
	@OneToMany<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span>, mappedBy <span style="color: #339933;">=</span> <span style="color: #0000ff;">"category"</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> getStockCategories<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>

	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStockCategories<span style="color: #009900;">(</span>Set<span style="color: #339933;">&lt;</span>StockCategory<span style="color: #339933;">&gt;</span> stockCategories<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategories</span> <span style="color: #339933;">=</span> stockCategories<span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>
...</pre>
</div>
</div>
<h5>StockCategory.java</h5>
<div>
<div>
<pre style="font-family: monospace;">@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock_category"</span>, catalog <span style="color: #339933;">=</span> <span style="color: #0000ff;">"mkyong"</span>,
        uniqueConstraints <span style="color: #339933;">=</span> @UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #009900;">{</span>
        <span style="color: #0000ff;">"STOCK_ID"</span>, <span style="color: #0000ff;">"CATEGORY_ID"</span> <span style="color: #009900;">}</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StockCategory <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> stockCategoryId<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Stock stock<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Category category<span style="color: #339933;">;</span>
	...
	@Id
	@GeneratedValue<span style="color: #009900;">(</span>strategy <span style="color: #339933;">=</span> IDENTITY<span style="color: #009900;">)</span>
	@Column<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_CATEGORY_ID"</span>, unique <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> getStockCategoryId<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockCategoryId</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>

	@ManyToOne<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span><span style="color: #009900;">)</span>
	@JoinColumn<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_ID"</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> Stock getStock<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stock</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>

	@ManyToOne<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span><span style="color: #009900;">)</span>
	@JoinColumn<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"CATEGORY_ID"</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> Category getCategory<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">category</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>
...</pre>
</div>
</div>
<p>The code is self-explanatory, all the @annotation are the XML mapping  tag substitution.</p>
<h3>Test It</h3>
<p>Run the example, both annotation and XML mapping file will generate  the same output. Hibernate inserts a row into the STOCK table, a row  into the CATEGORY table, and both relationship in STOCK_CATEGORY table.</p>
<div>
<div>
<pre style="font-family: monospace;">        Stock stock <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Stock<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        Category category <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Category<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        ...
        <span style="color: #006633;">session</span>.<span style="color: #006633;">save</span><span style="color: #009900;">(</span>stock<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        session.<span style="color: #006633;">save</span><span style="color: #009900;">(</span>category<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        ...
        <span style="color: #006633;">StockCategory</span> stockCategory <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StockCategory<span style="color: #009900;">(</span>stock, category<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        session.<span style="color: #006633;">save</span><span style="color: #009900;">(</span>stockCategory<span style="color: #009900;">)</span><span style="color: #339933;">;</span></pre>
</div>
</div>
<h5>Output</h5>
<div>
<div>
<pre style="font-family: monospace;">Hibernate:
    insert into mkyong.stock
    <span style="color: #7a0874; font-weight: bold;">(</span>STOCK_CODE, STOCK_NAME<span style="color: #7a0874; font-weight: bold;">)</span>
    values <span style="color: #7a0874; font-weight: bold;">(</span>?, ?<span style="color: #7a0874; font-weight: bold;">)</span>

Hibernate:
    insert into mkyong.category
    <span style="color: #7a0874; font-weight: bold;">(</span><span style="color: #000000; font-weight: bold;">`</span>DESC<span style="color: #000000; font-weight: bold;">`</span>, NAME<span style="color: #7a0874; font-weight: bold;">)</span>
    values <span style="color: #7a0874; font-weight: bold;">(</span>?, ?<span style="color: #7a0874; font-weight: bold;">)</span>

Hibernate:
    insert into mkyong.stock_category
    <span style="color: #7a0874; font-weight: bold;">(</span>CATEGORY_ID, STOCK_ID<span style="color: #7a0874; font-weight: bold;">)</span>
    values <span style="color: #7a0874; font-weight: bold;">(</span>?, ?<span style="color: #7a0874; font-weight: bold;">)</span></pre>
</div>
</div>
<img src="http://javabg.eu/?ak_action=api_record_view&id=431&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/hibernate-%e2%80%93-many-to-many-relationship-example/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Cascade – JPA &amp; Hibernate annotation common mistake</title>
		<link>http://javabg.eu/2010/02/cascade-%e2%80%93-jpa-hibernate-annotation-common-mistake/</link>
		<comments>http://javabg.eu/2010/02/cascade-%e2%80%93-jpa-hibernate-annotation-common-mistake/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 05:54:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[английски]]></category>
		<category><![CDATA[уроци]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=427</guid>
		<description><![CDATA[Mistake In the one-to-many example, many developers declared the JPA cascade options as following : ... @Entity @Table(name = "stock", catalog = "mkyong", uniqueConstraints = { @UniqueConstraint(columnNames = "STOCK_NAME"), @UniqueConstraint(columnNames = "STOCK_CODE") }) public class Stock implements java.io.Serializable { ... private Set&#60;StockDailyRecord&#62; stockDailyRecords = new HashSet&#60;StockDailyRecord&#62;(0); @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST,CascadeType.MERGE }, mappedBy = [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<h3>Mistake</h3>
<p>In the one-to-many example, many developers declared the JPA cascade  options as following :</p>
<div>
<div>
<pre style="font-family: monospace;">...
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span>, catalog <span style="color: #339933;">=</span> <span style="color: #0000ff;">"mkyong"</span>, uniqueConstraints <span style="color: #339933;">=</span> <span style="color: #009900;">{</span>
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_NAME"</span><span style="color: #009900;">)</span>,
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_CODE"</span><span style="color: #009900;">)</span> <span style="color: #009900;">}</span><span style="color: #009900;">)</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Stock <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
    ...
    <span style="color: #000000; font-weight: bold;">private</span> Set<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span> stockDailyRecords <span style="color: #339933;">=</span>
                                              <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>

    @OneToMany<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span>,
       cascade <span style="color: #339933;">=</span> <span style="color: #009900;">{</span>CascadeType.<span style="color: #006633;">PERSIST</span>,CascadeType.<span style="color: #006633;">MERGE</span> <span style="color: #009900;">}</span>,
       mappedBy <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span><span style="color: #009900;">)</span>
    <span style="color: #000000; font-weight: bold;">public</span> Set<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span> getStockDailyRecords<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockDailyRecords</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">}</span>

    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStockDailyRecords<span style="color: #009900;">(</span>Set<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span> stockDailyRecords<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockDailyRecords</span> <span style="color: #339933;">=</span> stockDailyRecords<span style="color: #339933;">;</span>
    <span style="color: #009900;">}</span>
    ...</pre>
</div>
</div>
<p>Save it with Hibernate session.</p>
<div>
<div>
<pre style="font-family: monospace;">        stockDailyRecords.<span style="color: #006633;">setStock</span><span style="color: #009900;">(</span>stock<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        stock.<span style="color: #006633;">getStockDailyRecords</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span>.<span style="color: #006633;">add</span><span style="color: #009900;">(</span>stockDailyRecords<span style="color: #009900;">)</span><span style="color: #339933;">;</span>

        session.<span style="color: #006633;">save</span><span style="color: #009900;">(</span>stock<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        session.<span style="color: #006633;">getTransaction</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span>.<span style="color: #006633;">commit</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span></pre>
</div>
</div>
<p>What the code trying to do is when you save a “stock”, it will save  the associated stockDailyRecords as well. Everything look fine, but <strong>THIS  IS NOT WORKING</strong>, the cascade options will not execute and save  the stockDailyRecords. Can you spot the mistake?</p>
<h3>Explanation</h3>
<p>Look in the code, <strong>@OneToMany</strong> is from JPA , it  expected a JPA cascade – <strong>javax.persistence.CascadeType</strong>.  However when you save it with Hibernate session, <strong>org.hibernate.engine.Cascade</strong> will do the following checking …</p>
<div>
<div>
<pre style="font-family: monospace;">	<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">(</span> style.<span style="color: #006633;">doCascade</span><span style="color: #009900;">(</span> action <span style="color: #009900;">)</span> <span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		cascadeProperty<span style="color: #009900;">(</span>
	          persister.<span style="color: #006633;">getPropertyValue</span><span style="color: #009900;">(</span> parent, i, entityMode <span style="color: #009900;">)</span>,
		  types<span style="color: #009900;">[</span>i<span style="color: #009900;">]</span>,
    	          style,
	          anything,
	          <span style="color: #000066; font-weight: bold;">false</span>
		<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span></pre>
</div>
</div>
<p>The Hibernate save process will causing a <strong>ACTION_SAVE_UPDATE</strong> action, but the JPA will pass a <strong>ACTION_PERSIST</strong> and <strong>ACTION_MERGE</strong>,  it will not match and causing the cascade failed to execute.</p>
<p>@see source code</p>
<ul>
<li><strong>org.hibernate.engine.Cascade</strong></li>
<li><strong>org.hibernate.engine.CascadeStyle</strong></li>
<li><strong>org.hibernate.engine.CascadingAction</strong></li>
</ul>
<h3>Solution</h3>
<p>Delete the JPA cascade – <strong>javax.persistence.CascadeType</strong>,  replace it with Hibernate cascade – <strong>org.hibernate.annotations.Cascade</strong>,  with <strong>CascadeType.SAVE_UPDATE</strong>.</p>
<div>
<div>
<pre style="font-family: monospace;">...
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span>, catalog <span style="color: #339933;">=</span> <span style="color: #0000ff;">"mkyong"</span>, uniqueConstraints <span style="color: #339933;">=</span> <span style="color: #009900;">{</span>
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_NAME"</span><span style="color: #009900;">)</span>,
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_CODE"</span><span style="color: #009900;">)</span> <span style="color: #009900;">}</span><span style="color: #009900;">)</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Stock <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
    ...
    <span style="color: #000000; font-weight: bold;">private</span> Set<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span> stockDailyRecords <span style="color: #339933;">=</span>
                                              <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>

    @OneToMany<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span>, mappedBy <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span><span style="color: #009900;">)</span>
    @Cascade<span style="color: #009900;">(</span><span style="color: #009900;">{</span>CascadeType.<span style="color: #006633;">SAVE_UPDATE</span><span style="color: #009900;">}</span><span style="color: #009900;">)</span>
    <span style="color: #000000; font-weight: bold;">public</span> Set<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span> getStockDailyRecords<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockDailyRecords</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">}</span>

    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStockDailyRecords<span style="color: #009900;">(</span>Set<span style="color: #339933;">&lt;</span>StockDailyRecord<span style="color: #339933;">&gt;</span> stockDailyRecords<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockDailyRecords</span> <span style="color: #339933;">=</span> stockDailyRecords<span style="color: #339933;">;</span>
    <span style="color: #009900;">}</span>
    ...</pre>
</div>
</div>
<p>Now, it work as what you expected.</p>
<h3>Conclusion</h3>
<p>It look like an incompatible issue between JPA and Hibernate cascade  annotation, if Hibernate is a JPA implementation, what may causing the  misunderstand in between?</p>
<img src="http://javabg.eu/?ak_action=api_record_view&id=427&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/cascade-%e2%80%93-jpa-hibernate-annotation-common-mistake/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hibernate Annotations</title>
		<link>http://javabg.eu/2010/02/hibernate-annotations/</link>
		<comments>http://javabg.eu/2010/02/hibernate-annotations/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 11:30:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[английски]]></category>
		<category><![CDATA[уроци]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=405</guid>
		<description><![CDATA[Hibernate Annotations This example is the same as the first example except that it uses annotations. There we first started by creating the .hbm.xml file, here there is no need to create it instead we will use annotations to do the object relational mapping. In addition to the already existing jar files you need to [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Hibernate Annotations</p>
<p>This example is the same as the first example except that it uses annotations. There we first started by creating the .hbm.xml file, here there is no need to create it instead we will use annotations to do the object relational mapping.</p>
<p>In addition to the already existing jar files you need to add the following jar files to the classpath.<br />
1.hibernate-commons-annotations.jar<br />
2.ejb3-persistence.jar<br />
3.hibernate-annotations.jar</p>
<p>Here we first start by creating the Course class. The Course class is shown below.</p>
<blockquote><p>01.package com.vaannila.course;<br />
02.<br />
03.import javax.persistence.Column;<br />
04.import javax.persistence.Entity;<br />
05.import javax.persistence.GeneratedValue;<br />
06.import javax.persistence.Id;<br />
07.import javax.persistence.Table;<br />
08.<br />
09.<br />
10.@Entity<br />
11.@Table(name=&#8220;COURSES&#8220;)<br />
12.public class Course {<br />
13.<br />
14.    private long courseId;<br />
15.    private String courseName;<br />
16.<br />
17.    public Course() {<br />
18.    }<br />
19.<br />
20.    public Course(String courseName) {<br />
21.    this.courseName = courseName;<br />
22.    }<br />
23.<br />
24.    @Id<br />
25.    @GeneratedValue<br />
26.    @Column(name=&#8220;COURSE_ID&#8220;)<br />
27.    public long getCourseId() {<br />
28.        return this.courseId;<br />
29.    }<br />
30.<br />
31.    public void setCourseId(long courseId) {<br />
32.        this.courseId = courseId;<br />
33.    }<br />
34.<br />
35.    @Column(name=&#8220;COURSE_NAME&#8220;, nullable=false)<br />
36.    public String getCourseName() {<br />
37.        return this.courseName;<br />
38.    }<br />
39.<br />
40.    public void setCourseName(String courseName) {<br />
41.        this.courseName = courseName;<br />
42.    }<br />
43.<br />
44.}</p></blockquote>
<p>As you can see we have used annotations in the code to do the object relational mapping. Hibernate supports EJB 3 persistence annotations. The EJB 3 annotations are contained in the javax.persistence package. If you avoid using Hibernate specific features in your application, then you will have the freedom to deploy your application in any environment that supports EJB 3. Anything imported from javax.persistence package tree is EJB 3 supported and anything imported from org.hibernate package tree is Hibernate specific.</p>
<p>The @Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.</p>
<p>The @Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If @Table annotation is not specified then Hibernate will by default use the class name as the table name.</p>
<p>The @Id annotation is used to specify the identifier property of the entity bean. The placement of the @Id annotation determines the default access strategy that Hibernate will use for the mapping. If the @Id annotation is placed over the field, then filed access will be used. Instead if it placed over the getter method of that field, then property access will be used. Here we use property access.</p>
<p>The @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.</p>
<p>The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Here the courseId property is mapped to COURSE_ID column in the COURSES table. If the @Column annotation is not specified by default the property name will be used as the column name.</p>
<p>The next change you need to do here is, instead of adding the .hbm.xml file to the hibernate.cfg.xml file, we add the fully qualified name of the annotated class to the mapping element.</p>
<blockquote><p>01.<?xml version="1.0" encoding="UTF-8"?><br />
02.<!DOCTYPE hibernate-configuration PUBLIC<br />
03.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"<br />
04.        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><br />
05.<hibernate-configuration><br />
06.    <session-factory><br />
07.
<property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver</property>
08.
<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost</property>
09.
<property name="hibernate.connection.username">sa</property>
10.
<property name="connection.password"></property>
11.
<property name="connection.pool_size">1</property>
12.
<property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property>
13.
<property name="show_sql">true</property>
14.
<property name="hbm2ddl.auto">create</property>
15.<br />
<mapping class="com.vaannila.course.Course" />
16.    </session-factory><br />
17.</hibernate-configuration></p></blockquote>
<p>The SessionFactory should be configured using the AnnotationConfiguration object instead of the Configuration object used with XML mappings.</p>
<blockquote><p>01.package com.vaannila.util;<br />
02.<br />
03.import org.hibernate.SessionFactory;<br />
04.import org.hibernate.cfg.AnnotationConfiguration;<br />
05.<br />
06.public class HibernateUtil {<br />
07.    private static final SessionFactory sessionFactory;<br />
08.    static {<br />
09.        try {<br />
10.            sessionFactory = new AnnotationConfiguration().configure()<br />
11.                    .buildSessionFactory();<br />
12.        } catch (Throwable ex) {<br />
13.            System.err.println(&#8222;Initial SessionFactory creation failed.&#8220; + ex);<br />
14.            throw new ExceptionInInitializerError(ex);<br />
15.        }<br />
16.    }<br />
17.<br />
18.    public static SessionFactory getSessionFactory() {<br />
19.        return sessionFactory;<br />
20.    }<br />
21.}</p></blockquote>
<p>These are the only few changes you need to do to make the example work using annotations. Now the big question is should you use annotations?</p>
<p>If your answer is yes to the following questions then you can use annotations in your project.</p>
<p>    * Do you have the flexibility to use Java 5 Environment?<br />
    * Do you have the knowledge of which production database you are going to use? If yes, you can use annotations, this brings in strong coupling. Inorder to support multiple databases, it is better to have the mapping information in a seperate xml file rather than using annotations. You can easily have multiple xml files each specific for a particular database rather than having a different sets of source codes.</p>
<p>Instead than keeping the mapping informations in a seperate file, using annotations you can always keep them along with the source code, in this way the soure code and mapping information will always be in sync. </p>
<img src="http://javabg.eu/?ak_action=api_record_view&id=405&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/hibernate-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate Tools Tutorial</title>
		<link>http://javabg.eu/2010/02/hibernate-tools-tutorial/</link>
		<comments>http://javabg.eu/2010/02/hibernate-tools-tutorial/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 11:29:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[английски]]></category>
		<category><![CDATA[уроци]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=401</guid>
		<description><![CDATA[Hibernate Example In this tutorial you will see how to persist the java objects using the Hibernate Object/Relational Mapping (ORM) framework. Hibernate automates ORM and considerably reduces the number of lines of code needed to persist the object in the database. This example demonstrates how to automatically generate code from the object/relational mapping file, thus [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<h1>Hibernate Example</h1>
<p>In this tutorial you will see how to persist the java objects using  the Hibernate Object/Relational Mapping (ORM) framework. Hibernate  automates ORM and considerably reduces the number of lines of code  needed to persist the object in the database. This example demonstrates  how to automatically generate code from the object/relational mapping  file, thus saving the developers time. This helps the developers to  focus on the business problem rather than doing repetitive coding work.</p>
<p>Hibernate uses XML document or the properties file to define the  object/relational mapping. The object/relational mapping file contains  the mapping between the Java object and the corresponding database  table. This example illustrates how to create the ORM using the XML  document.</p>
<p>First let&#8217;s setup the environment. I am using</p>
<ul>
<li> Eclipse IDE 3.4</li>
<li> Hibernate Core 3.3</li>
<li> Hibernate Tools 3.2</li>
<li> HSQLDB 1.8</li>
</ul>
<p>You can download the Hibernate Core and Hibernate Tools <a rel="nofollow" href="https://www.hibernate.org/6.html">here</a>.  HyperSQL DataBase is a 100% lightweight Java SQL Database Engine. You  can download HSQLDB from this site<a rel="nofollow" href="http://hsqldb.org/"> http://hsqldb.org/ </a>.</p>
<p>To install the Hibernate Tools, extract the <em>HibernateTools-3.X.zip</em> file and move all the files inside the features folder into the  features folder of the eclipse installation directory and  move all the  files inside the plugins folder into the plugins folder of the ecilpse  installation directory. Restart the eclipse.</p>
<p>First create a new Java project. Add the following lib files on the java  build path.</p>
<div id="highlighter_296156">
<div>
<div><code>01.</code><span><span style="margin-left: 0px ! important;"><code>antlr-2.7.6</code></span></span></div>
<div><code>02.</code><span><span style="margin-left: 0px ! important;"><code>commons-collections-3.1</code></span></span></div>
<div><code>03.</code><span><span style="margin-left: 0px ! important;"><code>dom4j-1.6.1</code></span></span></div>
<div><code>04.</code><span><span style="margin-left: 0px ! important;"><code>hibernate3</code></span></span></div>
<div><code>05.</code><span><span style="margin-left: 0px ! important;"><code>hsqldb</code></span></span></div>
<div><code>06.</code><span><span style="margin-left: 0px ! important;"><code>javassist-3.4.GA</code></span></span></div>
<div><code>07.</code><span><span style="margin-left: 0px ! important;"><code>jta-1.1</code></span></span></div>
<div><code>08.</code><span><span style="margin-left: 0px ! important;"><code>slf4j-api-1.5.6</code></span></span></div>
<div><code>09.</code><span><span style="margin-left: 0px ! important;"><code>slf4j-simple-1.5.6</code></span></span></div>
</div>
</div>
<p>The <em>hibernate3.jar</em> contains all the core hibernate files. The <em>hsqldb.jar</em> is used, to connect with the HSQL database, if you are using someother  database then you need to include that jar file instead of this. The <em>slf4j-api-1.5.6  jar</em> file is used for logging the informations, you can also use  other alternatives like log4j, to do that include that jar file instead  of <em>slf4j-simple-1.5.6</em> jar file to your classpath.</p>
<p>Once you have installed the hibernate tools, you will have the option to  change to Hibernate prespective.  Go to <em>Window -&gt; Open  Prespective -&gt; Other</em>, the following dialog box appears, select <em>Hibernate</em> and click the <em>Ok</em> button.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-1.gif" alt="" /></p>
<p>Now let&#8217;s see how to define the object/relational mapping using the  XML document. This  document has <em>hbm.xml</em> extension. We will now  create the object/relational mapping for the simple class that holds  course related details. To do that create a package <em>com.vaannila.course</em> in the <em>src</em> directory. The Hibernate XML mapping file will be  created in this directory. To create the mapping file, switch to  Hibernate prespective, right click the project folder and select <em>New  -&gt; Hibernate XML Mapping File(hbm.xml) </em></p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-2.gif" alt="" width="516" height="432" /></p>
<p>In the pop up window select the <em>course</em> folder, enter the file  name as <em>Course.hbm.xml</em> and click <em>Next</em>. In the next  window click <em>Finish</em>.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-3.gif" alt="" /></p>
<p>Add the following code to the<em> Course.hbm.xml</em> file.</p>
<div id="highlighter_93119">
<div>
<div><code>01.</code><span><span style="margin-left: 0px ! important;"><code>&lt;?</code><code>xml</code> <code>version</code><code>=</code><code>"1.0"</code><code>?&gt;</code></span></span></div>
<div><code>02.</code><span><span style="margin-left: 0px ! important;"><code>&lt;!DOCTYPE  hibernate-mapping PUBLIC</code></span></span></div>
<div><code>03.</code><span><span style="margin-left: 0px ! important;"><code>"-//Hibernate/Hibernate  Mapping DTD 3.0//EN"</code></span></span></div>
<div><code>04.</code><span><span style="margin-left: 0px ! important;"><code>"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;</code></span></span></div>
<div><code>05.</code><span><span style="margin-left: 0px ! important;"><code>&lt;</code><code>hibernate-mapping</code><code>&gt;</code></span></span></div>
<div><code>06.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>07.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>&lt;</code><code>class</code> <code>name</code><code>=</code><code>"com.vaannila.course.Course"</code> <code>table</code><code>=</code><code>"COURSES"</code><code>&gt;</code></span></span></div>
<div><code>08.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>meta</code> <code>attribute</code><code>=</code><code>"class-description"</code><code>&gt;</code></span></span></div>
<div><code>09.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>This class  contains the course details.</code></span></span></div>
<div><code>10.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;/</code><code>meta</code><code>&gt;</code></span></span></div>
<div><code>11.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>id</code> <code>name</code><code>=</code><code>"courseId"</code> <code>type</code><code>=</code><code>"long"</code> <code>column</code><code>=</code><code>"COURSE_ID"</code><code>&gt;</code></span></span></div>
<div><code>12.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>&lt;</code><code>generator</code> <code>class</code><code>=</code><code>"native"</code><code>/&gt;</code></span></span></div>
<div><code>13.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;/</code><code>id</code><code>&gt;</code></span></span></div>
<div><code>14.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"courseName"</code> <code>type</code><code>=</code><code>"string"</code> <code>column</code><code>=</code><code>"COURSE_NAME"</code> <code>not-null</code><code>=</code><code>"true"</code> <code>/&gt;</code></span></span></div>
<div><code>15.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>&lt;/</code><code>class</code><code>&gt;</code></span></span></div>
<div><code>16.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>17.</code><span><span style="margin-left: 0px ! important;"><code>&lt;/</code><code>hibernate-mapping</code><code>&gt;</code></span></span></div>
</div>
</div>
<p>The <em>hibernate-mapping</em> element is the root element. The <em>class</em> element is used to map the Java class with the database table. The Java  class name is specified using the <em>name</em> attribute of the <em>class</em> element and the database table name is specified using the <em>table</em> attribute of the <em>class</em> element. The <em>meta</em> element is  used to create the class description. The <em>id</em> element is used to  create the primary key. The <em>name</em> attribute of the <em>id</em> element refers to the property in the <em>Course</em> class and the <em>column</em> attribute refers to the column in the <em>COURSES</em> table. The <em>type</em> attribute holds the hibernate mapping type, this mapping types will  convert from Java to SQL data type and vice versa. The <em>generator</em> element within the <em>id</em> element is used to automatically  generate the primary key values. When the <em>class</em> attribute of  the generator element is set to <em>native, </em>hibernate picks either <em>identity</em>,  <em>sequence</em> or <em>hilo</em> algorithm depending upon the  capabilities of the  underlying database. The <em>property</em> element is used to link a  property in the Java class to  a column in the database table.</p>
<p>The next step is to create the Hibernate configuration file. On  startup, Hibernate looks for a file called <em>hibernate.cfg.xml</em> in  the root of the classpath. To create the Hibernate Configuration File,  right click the project, select <em>New -&gt; Hibernate Configuration  File (cfg.xml)</em></p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-4.gif" alt="" width="527" height="463" /></p>
<p>By default the file name will be <em>hibernate.cfg.xml</em>, select the <em>src</em> directory and click Next.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-5.gif" alt="" /></p>
<p>Select the database dialect  as <em>HSQL</em>. This property indicates  the particular SQL variant that Hibernate generates. Select the &#8222;<em>org.hsqldb.jdbcDriver</em>&#8220;  option for the driver class. Enter the connection url &#8222;<em>jdbc:hsqldb:hsql://localhost</em>&#8222;.  Enter the user name as &#8222;<em>sa</em>&#8220; and click <em>Finish</em>. These  properties specifies the necessary configuration for the JDBC  connection.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-6.gif" alt="" /></p>
<p>The <em>show_sql</em> option, if set to true will display all the  executed SQL queries on the console.</p>
<p>The property <em>hbm2ddl.auto</em>, if set to create, will drop and  re-create the database schema on startup.</p>
<p>In the end we add the <em>Course.hbm.xml</em> file to the  configuration. The implementation of the <em>hibernate.cfg.xml</em> file  is shown below.</p>
<div id="highlighter_534232">
<div>
<div><code>01.</code><span><span style="margin-left: 0px ! important;"><code>&lt;?</code><code>xml</code> <code>version</code><code>=</code><code>"1.0"</code> <code>encoding</code><code>=</code><code>"UTF-8"</code><code>?&gt;</code></span></span></div>
<div><code>02.</code><span><span style="margin-left: 0px ! important;"><code>&lt;!DOCTYPE  hibernate-configuration PUBLIC</code></span></span></div>
<div><code>03.</code><span><span style="margin-left: 0px ! important;"><code>"-//Hibernate/Hibernate  Configuration DTD 3.0//EN"</code></span></span></div>
<div><code>04.</code><span><span style="margin-left: 0px ! important;"><code>"http://hibernate.sourceforge.net/  hibernate-configuration-3.0.dtd"&gt;</code></span></span></div>
<div><code>05.</code><span><span style="margin-left: 0px ! important;"><code>&lt;</code><code>hibernate-configuration</code><code>&gt;</code></span></span></div>
<div><code>06.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>&lt;</code><code>session-factory</code><code>&gt;</code></span></span></div>
<div><code>07.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"hibernate.connection.driver_class"</code><code>&gt; org.hsqldb.jdbcDriver&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>08.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"hibernate.connection.url"</code><code>&gt;  jdbc:hsqldb:hsql://localhost&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>09.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"hibernate.connection.username"</code><code>&gt;sa&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>10.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"connection.password"</code><code>&gt;&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>11.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"connection.pool_size"</code><code>&gt;1&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>12.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"hibernate.dialect"</code><code>&gt;  org.hibernate.dialect.HSQLDialect&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>13.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"show_sql"</code><code>&gt;true&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>14.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>property</code> <code>name</code><code>=</code><code>"hbm2ddl.auto"</code><code>&gt;create&lt;/</code><code>property</code><code>&gt;</code></span></span></div>
<div><code>15.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>&lt;</code><code>mapping</code> <code>resource</code><code>=</code><code>"com/vaannila/course/Course.hbm.xml"</code><code>/&gt;</code></span></span></div>
<div><code>16.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>&lt;/</code><code>session-factory</code><code>&gt;</code></span></span></div>
<div><code>17.</code><span><span style="margin-left: 0px ! important;"><code>&lt;/</code><code>hibernate-configuration</code><code>&gt;</code></span></span></div>
</div>
</div>
<p>Once the Hibernate configuration file is created we need to create a  Hibernate console configuration. To do this right click the project  folder, select <em>New -&gt; Hibernate Console Configuration</em>.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-7.gif" alt="" width="583" height="612" /></p>
<p>The Hibernate Console configuration wizard appears.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-8.gif" alt="" /></p>
<p>By default the wizard will load the Hibernate configuration file  information. Just click the <em>Finish</em> button to create the  Hibernate console configuration.</p>
<p>Once the Hibernate console configuration is created, you can generate  code by selecting the <em>Hibernate Code Generation Configurations</em> option form the toolbar.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-9.gif" alt="" /></p>
<p>The Hibernate Code Generation wizard will be displayed. Now select  the output directory as the <em>src</em> directory.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-10.gif" alt="" /></p>
<p>In the Exporters tag select the &#8222;<em>Use Java 5 Syntax</em>&#8220; option and &#8222;<em>Domain  Code(.java)</em>&#8220; option.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-11.gif" alt="" width="537" height="432" /></p>
<p>In the Refresh tab select the options as shown below and click the <em>Run</em> button to generate the code.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-12.gif" alt="" width="533" height="495" /></p>
<p>The following <em>Course.java</em> class will be generated from the<em> Course.hbm.xml</em> mapping file.</p>
<div id="highlighter_710833">
<div>
<div><code>01.</code><span><span style="margin-left: 0px ! important;"><code>package</code> <code>com.vaannila.course;</code></span></span></div>
<div><code>02.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>03.</code><span><span style="margin-left: 0px ! important;"><code>// Generated May 30, 2009 6:49:31 AM by Hibernate Tools  3.2.4.GA</code></span></span></div>
<div><code>04.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>05.</code><span><span style="margin-left: 0px ! important;"><code>/**</code></span></span></div>
<div><code>06.</code><span><span style="margin-left: 0px ! important;"><code>*   This  class contains the course details.</code></span></span></div>
<div><code>07.</code><span><span style="margin-left: 0px ! important;"><code>* </code></span></span></div>
<div><code>08.</code><span><span style="margin-left: 0px ! important;"><code>*/</code></span></span></div>
<div><code>09.</code><span><span style="margin-left: 0px ! important;"><code>public</code> <code>class</code> <code>Course </code><code>implements</code> <code>java.io.Serializable {</code></span></span></div>
<div><code>10.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>11.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>private</code> <code>long</code> <code>courseId;</code></span></span></div>
<div><code>12.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>private</code> <code>String  courseName;</code></span></span></div>
<div><code>13.</code><span><code> </code><span style="margin-left: 32px ! important;"> </span></span></div>
<div><code>14.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>Course()  {</code></span></span></div>
<div><code>15.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>16.</code><span><code> </code><span style="margin-left: 32px ! important;"> </span></span></div>
<div><code>17.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>Course(String  courseName) {</code></span></span></div>
<div><code>18.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>this</code><code>.courseName = courseName;</code></span></span></div>
<div><code>19.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>20.</code><span><code> </code><span style="margin-left: 32px ! important;"> </span></span></div>
<div><code>21.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>long</code> <code>getCourseId() {</code></span></span></div>
<div><code>22.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>return</code> <code>this</code><code>.courseId;</code></span></span></div>
<div><code>23.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>24.</code><span><code> </code><span style="margin-left: 32px ! important;"> </span></span></div>
<div><code>25.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>void</code> <code>setCourseId(</code><code>long</code> <code>courseId) {</code></span></span></div>
<div><code>26.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>this</code><code>.courseId  = courseId;</code></span></span></div>
<div><code>27.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>28.</code><span><code> </code><span style="margin-left: 32px ! important;"> </span></span></div>
<div><code>29.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>String  getCourseName() {</code></span></span></div>
<div><code>30.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>return</code> <code>this</code><code>.courseName;</code></span></span></div>
<div><code>31.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>32.</code><span><code> </code><span style="margin-left: 32px ! important;"> </span></span></div>
<div><code>33.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>void</code> <code>setCourseName(String courseName) {</code></span></span></div>
<div><code>34.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>this</code><code>.courseName  = courseName;</code></span></span></div>
<div><code>35.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>36.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>37.</code><span><span style="margin-left: 0px ! important;"><code>}</code></span></span></div>
</div>
</div>
<p>Now create the <em>HibernateUtil</em> class. The <em>HibernateUtil</em> class helps in creating the <em>SessionFactory</em> from the Hibernate  configuration file. The <em>SessionFactory</em> is threadsafe, so it is  not necessary to obtain one for each thread. Here the static singleton  pattern is used to instantiate the <em>SessionFactory</em>. The  implementation of the <em>HibernateUtil</em> class is shown below.</p>
<div id="highlighter_804425">
<div>
<div><code>01.</code><span><span style="margin-left: 0px ! important;"><code>package</code> <code>com.vaannila.util;</code></span></span></div>
<div><code>02.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>03.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>org.hibernate.SessionFactory;</code></span></span></div>
<div><code>04.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>org.hibernate.cfg.Configuration;</code></span></span></div>
<div><code>05.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>06.</code><span><span style="margin-left: 0px ! important;"><code>public</code> <code>class</code> <code>HibernateUtil {</code></span></span></div>
<div><code>07.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>private</code> <code>static</code> <code>final</code> <code>SessionFactory  sessionFactory;</code></span></span></div>
<div><code>08.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>static</code> <code>{</code></span></span></div>
<div><code>09.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>try</code> <code>{</code></span></span></div>
<div><code>10.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>sessionFactory  = </code><code>new</code> <code>Configuration().configure()</code></span></span></div>
<div><code>11.</code><span><code> </code><span style="margin-left: 160px ! important;"><code>.buildSessionFactory();</code></span></span></div>
<div><code>12.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>catch</code> <code>(Throwable ex) {</code></span></span></div>
<div><code>13.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>System.err.println(</code><code>"Initial SessionFactory creation failed."</code> <code>+ ex);</code></span></span></div>
<div><code>14.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>throw</code> <code>new</code> <code>ExceptionInInitializerError(ex);</code></span></span></div>
<div><code>15.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>}</code></span></span></div>
<div><code>16.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>17.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>18.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>static</code> <code>SessionFactory getSessionFactory() {</code></span></span></div>
<div><code>19.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>return</code> <code>sessionFactory;</code></span></span></div>
<div><code>20.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>21.</code><span><span style="margin-left: 0px ! important;"><code>}</code></span></span></div>
</div>
</div>
<p>Now we will create a class with the <em>main()</em> method to run the  application.</p>
<div id="highlighter_450253">
<div>
<div><code>001.</code><span><span style="margin-left: 0px ! important;"><code>package</code> <code>com.vaannila.course;</code></span></span></div>
<div><code>002.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>003.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>java.util.List;</code></span></span></div>
<div><code>004.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>java.util.Iterator;</code></span></span></div>
<div><code>005.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>006.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>org.hibernate.HibernateException;</code></span></span></div>
<div><code>007.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>org.hibernate.Session;</code></span></span></div>
<div><code>008.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>org.hibernate.Transaction;</code></span></span></div>
<div><code>009.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>010.</code><span><span style="margin-left: 0px ! important;"><code>import</code> <code>com.vaannila.util.HibernateUtil;</code></span></span></div>
<div><code>011.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>012.</code><span><span style="margin-left: 0px ! important;"><code>public</code> <code>class</code> <code>Main {</code></span></span></div>
<div><code>013.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>014.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>static</code> <code>void</code> <code>main(String[]  args) {</code></span></span></div>
<div><code>015.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Main obj = </code><code>new</code> <code>Main();</code></span></span></div>
<div><code>016.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Long courseId1 = obj.saveCourse(</code><code>"Physics"</code><code>);</code></span></span></div>
<div><code>017.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Long courseId2 = obj.saveCourse(</code><code>"Chemistry"</code><code>);</code></span></span></div>
<div><code>018.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Long courseId3 = obj.saveCourse(</code><code>"Maths"</code><code>);</code></span></span></div>
<div><code>019.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>obj.listCourse();</code></span></span></div>
<div><code>020.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>obj.updateCourse(courseId3, </code><code>"Mathematics"</code><code>);</code></span></span></div>
<div><code>021.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>obj.deleteCourse(courseId2);</code></span></span></div>
<div><code>022.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>obj.listCourse();</code></span></span></div>
<div><code>023.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>024.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>025.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>Long  saveCourse(String courseName)</code></span></span></div>
<div><code>026.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>{</code></span></span></div>
<div><code>027.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Session session =  HibernateUtil.getSessionFactory().openSession();</code></span></span></div>
<div><code>028.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Transaction transaction = </code><code>null</code><code>;</code></span></span></div>
<div><code>029.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Long courseId = </code><code>null</code><code>;</code></span></span></div>
<div><code>030.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>try</code> <code>{</code></span></span></div>
<div><code>031.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction =  session.beginTransaction();</code></span></span></div>
<div><code>032.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>Course course  = </code><code>new</code> <code>Course();</code></span></span></div>
<div><code>033.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>course.setCourseName(courseName);</code></span></span></div>
<div><code>034.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>courseId =  (Long) session.save(course);</code></span></span></div>
<div><code>035.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.commit();</code></span></span></div>
<div><code>036.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>catch</code> <code>(HibernateException e) {</code></span></span></div>
<div><code>037.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.rollback();</code></span></span></div>
<div><code>038.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>e.printStackTrace();</code></span></span></div>
<div><code>039.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>finally</code> <code>{</code></span></span></div>
<div><code>040.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>session.close();</code></span></span></div>
<div><code>041.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>}</code></span></span></div>
<div><code>042.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>return</code> <code>courseId;</code></span></span></div>
<div><code>043.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>044.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>045.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>void</code> <code>listCourse()</code></span></span></div>
<div><code>046.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>{</code></span></span></div>
<div><code>047.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Session session =  HibernateUtil.getSessionFactory().openSession();</code></span></span></div>
<div><code>048.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Transaction transaction = </code><code>null</code><code>;</code></span></span></div>
<div><code>049.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>try</code> <code>{</code></span></span></div>
<div><code>050.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction =  session.beginTransaction();</code></span></span></div>
<div><code>051.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>List courses =  session.createQuery(</code><code>"from Course"</code><code>).list();</code></span></span></div>
<div><code>052.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>for</code> <code>(Iterator iterator = courses.iterator();  iterator.hasNext();)</code></span></span></div>
<div><code>053.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>{</code></span></span></div>
<div><code>054.</code><span><code> </code><span style="margin-left: 128px ! important;"><code>Course course = (Course) iterator.next();</code></span></span></div>
<div><code>055.</code><span><code> </code><span style="margin-left: 128px ! important;"><code>System.out.println(course.getCourseName());</code></span></span></div>
<div><code>056.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>}</code></span></span></div>
<div><code>057.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.commit();</code></span></span></div>
<div><code>058.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>catch</code> <code>(HibernateException e) {</code></span></span></div>
<div><code>059.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.rollback();</code></span></span></div>
<div><code>060.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>e.printStackTrace();</code></span></span></div>
<div><code>061.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>finally</code> <code>{</code></span></span></div>
<div><code>062.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>session.close();</code></span></span></div>
<div><code>063.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>}</code></span></span></div>
<div><code>064.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>065.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>066.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>void</code> <code>updateCourse(Long courseId, String courseName)</code></span></span></div>
<div><code>067.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>{</code></span></span></div>
<div><code>068.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Session session =  HibernateUtil.getSessionFactory().openSession();</code></span></span></div>
<div><code>069.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Transaction transaction = </code><code>null</code><code>;</code></span></span></div>
<div><code>070.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>try</code> <code>{</code></span></span></div>
<div><code>071.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction =  session.beginTransaction();</code></span></span></div>
<div><code>072.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>Course course  = (Course) session.get(Course.</code><code>class</code><code>, courseId);</code></span></span></div>
<div><code>073.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>course.setCourseName(courseName);</code></span></span></div>
<div><code>074.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.commit();</code></span></span></div>
<div><code>075.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>catch</code> <code>(HibernateException e) {</code></span></span></div>
<div><code>076.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.rollback();</code></span></span></div>
<div><code>077.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>e.printStackTrace();</code></span></span></div>
<div><code>078.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>finally</code> <code>{</code></span></span></div>
<div><code>079.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>session.close();</code></span></span></div>
<div><code>080.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>}</code></span></span></div>
<div><code>081.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>082.</code><span><span style="margin-left: 0px ! important;"> </span></span></div>
<div><code>083.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>public</code> <code>void</code> <code>deleteCourse(Long courseId)</code></span></span></div>
<div><code>084.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>{</code></span></span></div>
<div><code>085.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Session session =  HibernateUtil.getSessionFactory().openSession();</code></span></span></div>
<div><code>086.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>Transaction transaction = </code><code>null</code><code>;</code></span></span></div>
<div><code>087.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>try</code> <code>{</code></span></span></div>
<div><code>088.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction =  session.beginTransaction();</code></span></span></div>
<div><code>089.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>Course course  = (Course) session.get(Course.</code><code>class</code><code>, courseId);</code></span></span></div>
<div><code>090.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>session.delete(course);</code></span></span></div>
<div><code>091.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.commit();</code></span></span></div>
<div><code>092.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>catch</code> <code>(HibernateException e) {</code></span></span></div>
<div><code>093.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>transaction.rollback();</code></span></span></div>
<div><code>094.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>e.printStackTrace();</code></span></span></div>
<div><code>095.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>} </code><code>finally</code> <code>{</code></span></span></div>
<div><code>096.</code><span><code> </code><span style="margin-left: 96px ! important;"><code>session.close();</code></span></span></div>
<div><code>097.</code><span><code> </code><span style="margin-left: 64px ! important;"><code>}</code></span></span></div>
<div><code>098.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>}</code></span></span></div>
<div><code>099.</code><span><span style="margin-left: 0px ! important;"><code>}</code></span></span></div>
</div>
</div>
<p>The first call to the <em>openSession()</em> method begins the  session. The <em>session.beginTransaction() </em>method is used to start  a new transaction. Here we have four different methods to perform the  CRUD operations.</p>
<p>The <em>saveCourse()</em> method is used to save a new <em>Course</em> object to the database.  In the <em>saveCourse()</em>method a new  object of the <em>Course</em> class is created and the <em>courseName</em> value is set, the <em>courseId</em> value is auto generated so the  value needn&#8217;t be set here. The<em> session.save()</em> 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 <em>courseId</em> value is of  type <em>long</em> so we typecast the returned value to <em>Long</em>.  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 <em>listCourse()</em> method is used to list all the courses. The  <em>session.createQuery()</em> method is used to create a query object  which helps in retrieving the persistant objects. Here we use Hibernate  Query Language (HQL). &#8222;<em>from Course</em>&#8220; returns a list of all the  courses in the COURSES 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 courses and display them on the console.</p>
<p>The <em>updateCourse()</em> method is used to update the course name.  It takes <em>the courseId</em> and the new <em>courseName</em> as input  parameters. The <em>courseId</em> is used to retrive the actual course  object using the <em>session.get()</em> method. The<em> session.get()</em> method takes the class name and the id value as the input parameter and  returns the corresponding Object. Here we set the new course name to  the <em>Course</em> object and commit the transaction. We need not  explicitly call the <em>session.save() </em>method to persist the  object. Hibernate will automatically update the database when  the state  of the persistant object is modified inside a transaction. This feature  of Hibernate is called <em>automatic dirty checking</em>.</p>
<p>The <em>deleteCourse()</em> method is used to delete a <em>Course</em> object. This method is similar to the <em>updateCourse()</em> method,  here instead of updating the object we call the <em>session.delete()</em> method to delete a persistant object.</p>
<p>The figure below shows the final directory structure of the example.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-18.gif" alt="" /></p>
<p>To run the example, first start the HSQLDB server. To start the HSQLDB  server, run the command prompt, go to the hsqldb directory and execute  the following command.</p>
<div id="highlighter_865003">
<div>
<div><code>1.</code><span><span style="margin-left: 0px ! important;"><code>java -cp ./lib/hsqldb.jar  org.hsqldb.Server</code></span></span></div>
</div>
</div>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-13.gif" alt="" width="528" height="219" /></p>
<p>After starting the server, run the <em>Main</em> class. On startup the  database schema will be created and the following actions will happen.</p>
<div id="highlighter_507672">
<div>
<div><code>01.</code><span><span style="margin-left: 0px ! important;"><code>public</code> <code>static</code> <code>void</code> <code>main(String[]  args) {</code></span></span></div>
<div><code>02.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>Main obj = </code><code>new</code> <code>Main();</code></span></span></div>
<div><code>03.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>Long courseId1 = obj.saveCourse(</code><code>"Physics"</code><code>);</code></span></span></div>
<div><code>04.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>Long courseId2 = obj.saveCourse(</code><code>"Chemistry"</code><code>);</code></span></span></div>
<div><code>05.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>Long courseId3 = obj.saveCourse(</code><code>"Maths"</code><code>);</code></span></span></div>
<div><code>06.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>obj.listCourse();</code></span></span></div>
<div><code>07.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>obj.updateCourse(courseId3, </code><code>"Mathematics"</code><code>);</code></span></span></div>
<div><code>08.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>obj.deleteCourse(courseId2);</code></span></span></div>
<div><code>09.</code><span><code> </code><span style="margin-left: 32px ! important;"><code>obj.listCourse();</code></span></span></div>
<div><code>10.</code><span><span style="margin-left: 0px ! important;"><code>}</code></span></span></div>
</div>
</div>
<p>Each time on startup the database schema will be droped and  recreated, if you want to use the existing one change the value of <em>hbm2ddl.auto</em> option to update.</p>
<p>The SQL statement generated  gets displayed on the console. This is  set using the<em> show_sql </em>option in the hibernate configuration  file.</p>
<div id="highlighter_406735">
<div>
<div><code>01.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate: insert into COURSES  (COURSE_ID, COURSE_NAME) values (null, ?)</code></span></span></div>
<div><code>02.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  call identity()</code></span></span></div>
<div><code>03.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)</code></span></span></div>
<div><code>04.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  call identity()</code></span></span></div>
<div><code>05.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)</code></span></span></div>
<div><code>06.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  call identity()</code></span></span></div>
<div><code>07.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  select course0_.COURSE_ID as COURSE1_0_, course0_.COURSE_NAME as  COURSE2_0_ from COURSES course0_</code></span></span></div>
<div><code>08.</code><span><span style="margin-left: 0px ! important;"><code>Physics</code></span></span></div>
<div><code>09.</code><span><span style="margin-left: 0px ! important;"><code>Chemistry</code></span></span></div>
<div><code>10.</code><span><span style="margin-left: 0px ! important;"><code>Maths</code></span></span></div>
<div><code>11.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  select course0_.COURSE_ID as COURSE1_0_0_, course0_.COURSE_NAME as  COURSE2_0_0_ from COURSES course0_ where course0_.COURSE_ID=?</code></span></span></div>
<div><code>12.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  update COURSES set COURSE_NAME=? where COURSE_ID=?</code></span></span></div>
<div><code>13.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  select course0_.COURSE_ID as COURSE1_0_0_, course0_.COURSE_NAME as  COURSE2_0_0_ from COURSES course0_ where course0_.COURSE_ID=?</code></span></span></div>
<div><code>14.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  delete from COURSES where COURSE_ID=?</code></span></span></div>
<div><code>15.</code><span><span style="margin-left: 0px ! important;"><code>Hibernate:  select course0_.COURSE_ID as COURSE1_0_, course0_.COURSE_NAME as  COURSE2_0_ from COURSES course0_</code></span></span></div>
<div><code>16.</code><span><span style="margin-left: 0px ! important;"><code>Physics</code></span></span></div>
<div><code>17.</code><span><span style="margin-left: 0px ! important;"><code>Mathematics</code></span></span></div>
</div>
</div>
<p>Now let&#8217;s check whether the database schema is created and the data is  inserted into the <em>COURSES</em> table or not. Open a new command  prompt, go to the hsqldb installed directory and type the following  command.</p>
<div id="highlighter_749025">
<div>
<div><code>1.</code><span><span style="margin-left: 0px ! important;"><code>java -cp ./lib/hsqldb.jar  org.hsqldb.util.DatabaseManager</code></span></span></div>
</div>
</div>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-14.gif" alt="" width="480" height="96" /></p>
<p>The following dialog box pops up. Select the Type as &#8222;<em>HSQL Database  Engine Server</em>&#8220; and click <em>Ok</em>.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-15.gif" alt="" /></p>
<p>The HSQL Databse Manager window opens. Here you can enter the following  SQL statement, and see the data is successfully stored in the <em>COURSES</em> table.</p>
<p><img src="http://www.vaannila.com/images/hibernate/hibernate-example-pic-19.gif" alt="" width="576" height="424" /></p>
<p>To shutdown the HSQLDB properly enter &#8222;<em>shutdown</em>&#8220; and click the <em>Execute</em> button. Alternatively you can also shutdown programmatically by closing  the SessionFactory, using <em>HibernateUtil.getSessionFactory().close()</em> method.</p>
<p>You can download the source code of this example by clicking the  Download link below.</p>
<img src="http://javabg.eu/?ak_action=api_record_view&id=401&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/hibernate-tools-tutorial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hibernate – One-to-one relationship example</title>
		<link>http://javabg.eu/2010/02/hibernate-%e2%80%93-one-to-one-relationship-example/</link>
		<comments>http://javabg.eu/2010/02/hibernate-%e2%80%93-one-to-one-relationship-example/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 11:22:41 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[английски]]></category>
		<category><![CDATA[уроци]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=398</guid>
		<description><![CDATA[A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. “One-to-one” example This is a one-to-one relationship table design, a STOCK table contains exactly one record in STOCK_DETAIL table. Both tables have the same Stock_Id as primary key. In STOCK_DETAIL table, Stock_Id is the primary key and also a [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<blockquote><p>A one-to-one relationships occurs when one entity is  related to exactly one occurrence in another entity.</p></blockquote>
<h3>“One-to-one” example</h3>
<p>This is a <strong>one-to-one</strong> relationship table design, a  STOCK table contains exactly one record in STOCK_DETAIL table. Both  tables have the same Stock_Id as primary key. <strong>In STOCK_DETAIL  table, Stock_Id is the primary key and also a foreign key to STOCK table</strong>.  This is one of the common ways to define one-to-one relationship. <a href="http://www.mkyong.com/mysql/how-to-define-one-to-one-relationship-in-mysql/" target="_blank">More detail…</a></p>
<div><img title="one-to-one-relationship" src="http://www.mkyong.com/wp-content/uploads/2010/01/one-to-one-relationship.jpg" alt="one-to-one-relationship" /></div>
<h3>Hibernate implementation</h3>
<p>In Hibernate, this “one-to-one” relationship can implemented in two  ways :</p>
<ul>
<li>Hibernate XML Mapping file</li>
<li>Hibernate Annotation</li>
</ul>
<h4>1. Hibernate XML mapping file</h4>
<p>In XML mapping way, you need two Java classes to hold the table data.</p>
<ul>
<li>Stock.java -&gt; STOCK table</li>
<li>StockDetail.java -&gt; STOCK_DETAIL table</li>
</ul>
<p>and two XML mapping files to describe the table relationship.</p>
<ul>
<li>Stock.hbm.xml -&gt; STOCK table</li>
<li>StockDetail.hbm.xml -&gt; STOCK_DETAIL table</li>
</ul>
<h5>Stock.java</h5>
<div>
<div>
<pre style="font-family: monospace;">...
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Stock <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">private</span> StockDetail stockDetail<span style="color: #339933;">;</span>
	...
	<span style="color: #000000; font-weight: bold;">public</span> StockDetail getStockDetail<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockDetail</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStockDetail<span style="color: #009900;">(</span>StockDetail stockDetail<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockDetail</span> <span style="color: #339933;">=</span> stockDetail<span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span></pre>
</div>
</div>
<h5>StockDetail.java</h5>
<div>
<div>
<pre style="font-family: monospace;">...
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StockDetail <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">private</span> Stock stock<span style="color: #339933;">;</span>
        ...
        <span style="color: #000000; font-weight: bold;">public</span> Stock getStock<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stock</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>

	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setStock<span style="color: #009900;">(</span>Stock stock<span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stock</span> <span style="color: #339933;">=</span> stock<span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span></pre>
</div>
</div>
<h5>Stock.hbm.xml</h5>
<div>
<div>
<pre style="font-family: monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"com.mkyong.common.Stock"</span> <span style="color: #000066;">table</span>=<span style="color: #ff0000;">"stock"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stockId"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"java.lang.Integer"</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"STOCK_ID"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;generator</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"identity"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        ...
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;one-to-one</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stockDetail"</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"com.mkyong.common.StockDetail"</span> </span>
<span style="color: #009900;">         <span style="color: #000066;">cascade</span>=<span style="color: #ff0000;">"save-update"</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/one-to-one<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        ...</pre>
</div>
</div>
<h5>StockDetail.hbm.xml</h5>
<div>
<div>
<pre style="font-family: monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"com.mkyong.common.StockDetail"</span> <span style="color: #000066;">table</span>=<span style="color: #ff0000;">"stock_detail"</span> ...<span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stockId"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"java.lang.Integer"</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;column</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"STOCK_ID"</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;generator</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"foreign"</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"property"</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>stock<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/generator<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;one-to-one</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"stock"</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">"com.mkyong.common.Stock"</span> </span>
<span style="color: #009900;">        <span style="color: #000066;">constrained</span>=<span style="color: #ff0000;">"true"</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/one-to-one<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        ...</pre>
</div>
</div>
<p>The main difficulty with <strong>one-to-one</strong> relationship is  ensuring both are assigned the same primary key. In StockDetail.hbm.xml,  a special <strong>foreign identifier generator</strong> is declared, it  will know get the primary key value from STOCK table. With  constrained=”true”, it ensure the Stock must exists.</p>
<h4>2. Hibernate annotation</h4>
<p>In annotation way, only two classes are required, all the  relationships are declared inside the Java classes.</p>
<ul>
<li>Stock.java -&gt; STOCK table</li>
<li>StockDetail.java -&gt; STOCK_DETAIL table</li>
</ul>
<h5>Stock.java</h5>
<div>
<div>
<pre style="font-family: monospace;">...
@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span>, catalog <span style="color: #339933;">=</span> <span style="color: #0000ff;">"mkyong"</span>, uniqueConstraints <span style="color: #339933;">=</span> <span style="color: #009900;">{</span>
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_NAME"</span><span style="color: #009900;">)</span>,
		@UniqueConstraint<span style="color: #009900;">(</span>columnNames <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_CODE"</span><span style="color: #009900;">)</span> <span style="color: #009900;">}</span><span style="color: #009900;">)</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Stock <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">private</span> StockDetail stockDetail<span style="color: #339933;">;</span>
        ...
	@Id
	@GeneratedValue<span style="color: #009900;">(</span>strategy <span style="color: #339933;">=</span> GenerationType.<span style="color: #006633;">IDENTITY</span><span style="color: #009900;">)</span>
	@Column<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_ID"</span>, unique <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> getStockId<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockId</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>

	@OneToOne<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span>, mappedBy <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span><span style="color: #009900;">)</span>
	@Cascade<span style="color: #009900;">(</span><span style="color: #009900;">{</span>CascadeType.<span style="color: #006633;">SAVE_UPDATE</span><span style="color: #009900;">}</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> StockDetail getStockDetail<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockDetail</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span></pre>
</div>
</div>
<h5>StockDetail.java</h5>
<div>
<div>
<pre style="font-family: monospace;">@<span style="color: #003399;">Entity</span>
@Table<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock_detail"</span>, catalog <span style="color: #339933;">=</span> <span style="color: #0000ff;">"mkyong"</span><span style="color: #009900;">)</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StockDetail <span style="color: #000000; font-weight: bold;">implements</span> java.<span style="color: #006633;">io</span>.<span style="color: #003399;">Serializable</span> <span style="color: #009900;">{</span>
	<span style="color: #000000; font-weight: bold;">private</span> Stock stock<span style="color: #339933;">;</span>
        ...
	@GenericGenerator<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"generator"</span>,
            strategy <span style="color: #339933;">=</span> <span style="color: #0000ff;">"foreign"</span>,
            parameters <span style="color: #339933;">=</span> @Parameter<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"property"</span>, value <span style="color: #339933;">=</span> <span style="color: #0000ff;">"stock"</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span>
	@Id
	@GeneratedValue<span style="color: #009900;">(</span>generator <span style="color: #339933;">=</span> <span style="color: #0000ff;">"generator"</span><span style="color: #009900;">)</span>
	@Column<span style="color: #009900;">(</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">"STOCK_ID"</span>, unique <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span>, nullable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">)</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> getStockId<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stockId</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span>

	@OneToOne<span style="color: #009900;">(</span>fetch <span style="color: #339933;">=</span> FetchType.<span style="color: #006633;">LAZY</span><span style="color: #009900;">)</span>
	@PrimaryKeyJoinColumn
	<span style="color: #000000; font-weight: bold;">public</span> Stock getStock<span style="color: #009900;">(</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">stock</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">}</span></pre>
</div>
</div>
<p>The code is self-explanatory, all the @annotation are the XML mapping  tag substitution.</p>
<h3>Test It</h3>
<p>Run the example, both annotation and XML mapping file will generate  the same output. Hibernate inserts a row into the STOCK table and a row  into the STOCK_DETAIL table.</p>
<div>
<div>
<pre style="font-family: monospace;">        Stock stock <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Stock<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>

        stock.<span style="color: #006633;">setStockCode</span><span style="color: #009900;">(</span><span style="color: #0000ff;">"4715"</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        stock.<span style="color: #006633;">setStockName</span><span style="color: #009900;">(</span><span style="color: #0000ff;">"GENM"</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>

        StockDetail stockDetail <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StockDetail<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        stockDetail.<span style="color: #006633;">setCompName</span><span style="color: #009900;">(</span><span style="color: #0000ff;">"GENTING Malaysia"</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        stockDetail.<span style="color: #006633;">setCompDesc</span><span style="color: #009900;">(</span><span style="color: #0000ff;">"Best resort in the world"</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        stockDetail.<span style="color: #006633;">setListedDate</span><span style="color: #009900;">(</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>

        stock.<span style="color: #006633;">setStockDetail</span><span style="color: #009900;">(</span>stockDetail<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
        stockDetail.<span style="color: #006633;">setStock</span><span style="color: #009900;">(</span>stock<span style="color: #009900;">)</span><span style="color: #339933;">;</span>

        session.<span style="color: #006633;">save</span><span style="color: #009900;">(</span>stock<span style="color: #009900;">)</span><span style="color: #339933;">;</span></pre>
</div>
</div>
<h5>Output</h5>
<div>
<div>
<pre style="font-family: monospace;">Hibernate:
    <span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> mkyong<span style="color: #66cc66;">.</span>stock
    <span style="color: #66cc66;">(</span>STOCK_CODE<span style="color: #66cc66;">,</span> STOCK_NAME<span style="color: #66cc66;">)</span>
    <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">(</span>?<span style="color: #66cc66;">,</span> ?<span style="color: #66cc66;">)</span>

Hibernate:
    <span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> mkyong<span style="color: #66cc66;">.</span>stock_detail
    <span style="color: #66cc66;">(</span>COMP_NAME<span style="color: #66cc66;">,</span> COMP_DESC<span style="color: #66cc66;">,</span> REMARK<span style="color: #66cc66;">,</span> LISTED_DATE<span style="color: #66cc66;">,</span> STOCK_ID<span style="color: #66cc66;">)</span>
    <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">(</span>?<span style="color: #66cc66;">,</span> ?<span style="color: #66cc66;">,</span> ?<span style="color: #66cc66;">,</span> ?<span style="color: #66cc66;">,</span> ?<span style="color: #66cc66;">)</span></pre>
</div>
</div>
<img src="http://javabg.eu/?ak_action=api_record_view&id=398&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/hibernate-%e2%80%93-one-to-one-relationship-example/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Different between session.get() and session.load()</title>
		<link>http://javabg.eu/2010/02/different-between-session-get-and-session-load/</link>
		<comments>http://javabg.eu/2010/02/different-between-session-get-and-session-load/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 11:22:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[английски]]></category>
		<category><![CDATA[уроци]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=396</guid>
		<description><![CDATA[Often times, you will notice Hibernate developers mix use of session.get() and session load(), do you wonder what’s the different and when you should use either of it? Different between session.get() and session.load() Actually, both functions are use to retrieve an object with different mechanism, of course. 1. session.load() It will always return a “proxy” [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Often times, you will notice Hibernate developers mix use of <strong>session.get()</strong> and <strong>session load()</strong>, do you wonder what’s the different  and when you should use either of it?</p>
<h3>Different between session.get() and session.load()</h3>
<p>Actually, both functions are use to retrieve an object with different  mechanism, of course.</p>
<h4>1. session.load()</h4>
<ul>
<li>It will always return a “<strong>proxy</strong>” (Hibernate term)  without hitting the database. In Hibernate, proxy is an object with the  given identifier value, its properties are not initialized yet, it just  look like a temporary fake object.</li>
<li>If no row found , it will throws an <strong>ObjectNotFoundException</strong>.</li>
</ul>
<h4>2. session.get()</h4>
<ul>
<li>It always <strong>hit the database</strong> and return the real  object, an object that represent the database row, not proxy.</li>
<li>If no row found , it return <strong>null</strong>.</li>
</ul>
<h3>It’s about performance</h3>
<p>Hibernate create anything for some reasons, when you do the  association, it’s normal to obtain retrieve an object (persistent  instance) from database and assign it as a reference to another object,  just to maintain the relationship. Let’s go through some examples to  understand in what situation you should use <strong>session.load()</strong>.</p>
<h4>1. session.get()</h4>
<p>For example, in a Stock application , Stock and StockTransactions  should have a “one-to-many” relationship, when you want to save a stock  transaction, it’s common to declared something like below</p>
<div>
<div>
<pre style="font-family: monospace;">    	   Stock stock <span style="color: #339933;">=</span> <span style="color: #009900;">(</span>Stock<span style="color: #009900;">)</span>session.<span style="color: #006633;">get</span><span style="color: #009900;">(</span>Stock.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Integer</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
           StockTransaction stockTransactions <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StockTransaction<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
           <span style="color: #666666; font-style: italic;">//set stockTransactions detail</span>
           stockTransactions.<span style="color: #006633;">setStock</span><span style="color: #009900;">(</span>stock<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
           session.<span style="color: #006633;">save</span><span style="color: #009900;">(</span>stockTransactions<span style="color: #009900;">)</span><span style="color: #339933;">;</span></pre>
</div>
</div>
<h4>Output</h4>
<div>
<div>
<pre style="font-family: monospace;">Hibernate:
    <span style="color: #000000; font-weight: bold;">select</span> ... from mkyong.stock stock0_
    where stock0_.STOCK_ID=?
Hibernate:
    insert into mkyong.stock_transaction <span style="color: #7a0874; font-weight: bold;">(</span>...<span style="color: #7a0874; font-weight: bold;">)</span>
    values <span style="color: #7a0874; font-weight: bold;">(</span>?, ?, ?, ?, ?, ?<span style="color: #7a0874; font-weight: bold;">)</span></pre>
</div>
</div>
<p>In session.get(), Hibernate will hit the database to retrieve the  Stock object and put it as a reference to StockTransaction. However,  this save process is extremely high demand, there may be thousand or  million transactions per hour, do you think is this necessary to hit the  database to retrieve the Stock object everything save a stock  transaction record? After all you just need the Stock’s Id as a  reference to StockTransaction.</p>
<h4>2. session.load()</h4>
<p>In above scenario, <strong>session.load()</strong> will be your good  solution, let’s see the example,</p>
<div>
<div>
<pre style="font-family: monospace;">    	   Stock stock <span style="color: #339933;">=</span> <span style="color: #009900;">(</span>Stock<span style="color: #009900;">)</span>session.<span style="color: #006633;">load</span><span style="color: #009900;">(</span>Stock.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Integer</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
           StockTransaction stockTransactions <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StockTransaction<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
           <span style="color: #666666; font-style: italic;">//set stockTransactions detail</span>
           stockTransactions.<span style="color: #006633;">setStock</span><span style="color: #009900;">(</span>stock<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
           session.<span style="color: #006633;">save</span><span style="color: #009900;">(</span>stockTransactions<span style="color: #009900;">)</span><span style="color: #339933;">;</span></pre>
</div>
</div>
<h4>Output</h4>
<div>
<div>
<pre style="font-family: monospace;">Hibernate:
    insert into mkyong.stock_transaction <span style="color: #7a0874; font-weight: bold;">(</span>...<span style="color: #7a0874; font-weight: bold;">)</span>
    values <span style="color: #7a0874; font-weight: bold;">(</span>?, ?, ?, ?, ?, ?<span style="color: #7a0874; font-weight: bold;">)</span></pre>
</div>
</div>
<p>In session.load(), Hibernate will not hit the database (no select  statement in output) to retrieve the Stock object, it will return a  Stock proxy object – a fake object with given identify value. In this  scenario, a proxy object is enough for to save a stock transaction  record.</p>
<h3>Exception</h3>
<p>In exception case, see the examples</p>
<h4>session.load()</h4>
<div>
<div>
<pre style="font-family: monospace;">Stock stock <span style="color: #339933;">=</span> <span style="color: #009900;">(</span>Stock<span style="color: #009900;">)</span>session.<span style="color: #006633;">load</span><span style="color: #009900;">(</span>Stock.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Integer</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">100</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//proxy</span>

 <span style="color: #666666; font-style: italic;">//initialize proxy, no row for id 100, throw ObjectNotFoundException</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">(</span>stock.<span style="color: #006633;">getStockCode</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span></pre>
</div>
</div>
<p>It will always return a proxy object with the given identity value,  even the identity value is not exists in database. However, when you try  to initialize a proxy by retrieve it’s properties from database, it  will hit the database with select statement. If no row is found, a <strong>ObjectNotFoundException </strong>will throw.</p>
<div>
<div>
<pre style="font-family: monospace;">org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
<span style="color: #7a0874; font-weight: bold;">[</span>com.mkyong.common.Stock<span style="color: #666666; font-style: italic;">#100]</span></pre>
</div>
</div>
<h4>session.get()</h4>
<div>
<div>
<pre style="font-family: monospace;"><span style="color: #666666; font-style: italic;">//return null if not found</span>
Stock stock <span style="color: #339933;">=</span> <span style="color: #009900;">(</span>Stock<span style="color: #009900;">)</span>session.<span style="color: #006633;">get</span><span style="color: #009900;">(</span>Stock.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Integer</span><span style="color: #009900;">(</span><span style="color: #cc66cc;">100</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">(</span>stock.<span style="color: #006633;">getStockCode</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//java.lang.NullPointerException</span></pre>
</div>
</div>
<p>It will always return null , if the identity value is not found in  database.</p>
<h3>Conclusion</h3>
<p>There are no always correct solution, you have to understand the  differential in between, and decide which method is best fix in your  application.</p>
<img src="http://javabg.eu/?ak_action=api_record_view&id=396&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/different-between-session-get-and-session-load/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

