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

<channel>
	<title>JavaBeat &#187; JPA</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/jpa/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Struts 2.0 and JPA Integration</title>
		<link>http://www.javabeat.net/2011/02/struts-2-0-and-jpa-integration/</link>
		<comments>http://www.javabeat.net/2011/02/struts-2-0-and-jpa-integration/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 13:25:18 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JPA]]></category>
		<category><![CDATA[Struts 2.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=564</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction Struts 2.0 is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on MVC Model 2 design pattern. Dispatcher Filter is the front controller for the struts2 based applications. Struts 2.0 has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support for [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><h2>Introduction</h2>
<p><strong>Struts 2.0</strong> is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on <strong>MVC Model 2 </strong>design pattern. Dispatcher Filter is the front controller for the struts2 based applications. <strong><a href="http://www.javabeat.net/articles/67-struts-20-introduction-and-validations-using-annotatio-1.html">Struts 2.0</a></strong> has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support for many different result types.</p>
<p>Struts can be used to build the user interface tier of the enterprise application. Whereas, any of the popular ORMs like Hibernate, JPA, iBatis can be used for the persistence tier of the application. Struts2 provides easy integration with these persistence tier frameworks.</p>
<p>This article demonstrates the integration of <strong><a href="http://www.javabeat.net/articles/67-struts- 20-introduction-and-validations-using-annotatio-1.html">Struts 2.0</a></strong> applications with the <strong><a href="http://www.javabeat.net/articles/5-introduction-to-java-persistence-apijpa-1.html">Java Persistence API (JPA)</a></strong>. The concept is explained with the help of a sample application. Knowledge of <strong>JPA and Struts 2.0</strong> is the prerequisite for this article.</p>
<h2>Development Environment</h2>
<ul>
<li>NetBeans IDE 6.8</li>
<li>GlassFish V2.x</li>
<li>Apache Derby Database</li>
</ul>
<h2>Project Structure</h2>
<p>The sample application developed in this article is &#8220;StrutsJPADemo&#8221; where an employee details are persisted to the database with the help of JPA.</p>
<p><strong>Libraries/Jar Files Required</strong></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li>Struts 2.0 jar files</li>
<li>JPA jar files</li>
<li>Jar file for the database driver (derbyclient.jar, in our case) The<br />
complete application structure is shown below:</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2011/02/15.jpg"><img class="aligncenter size-medium wp-image-1045" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/02/15-249x300.jpg" alt="" width="249" height="300" /></a></li>
<li><center></center></li>
<li>The User Interface (JSP pages) is created in the “Web Pages” directory. The java classes (Actions, Entities, Service classes, Resource Bundles, struts.xml) are created in the “Source Packages” directory. The required jar files are present in the “Libraries” directory. The web application deployment descriptor “web.xml” is created by the IDE in the “WEB-INF” subdirectory of “Web Pages”. This sample application stores the employee details into the Derby database.</li>
</ul>
<h2>Environment Set Up</h2>
<p>Once the web application is created and all the required libraries are added to the classpath, we can start working on the different components of the application.</p>
<p>Before we start working on the different application components like JSP pages and Java classes, we must first configure the following resources in the application server:</p>
<ol type="1">
<li><strong>javax.transaction.UserTransaction</strong>
<ol type="a">
<ol type="a">
<li>In our application, we have created a UserTransaction and bound the same in JNDI with the name “UserTransaction”. The snapshot given below shows the same.</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2011/02/24.jpg"><img class="aligncenter size-medium wp-image-1047" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/02/24-300x146.jpg" alt="" width="300" height="146" /></a></li>
</ol>
</ol>
<p><center></center></li>
<li><strong>Connection Pool &amp; DSN</strong>
<ol type="a">
<ol type="a">
<li>For the database, we have created a connection pool in the application server to connect to ScrambleDatabase in the local machine running at port number 1527. The connection pool is bound to the name<br />
“scramblePool” as shown in the snapshot below.</li>
</ol>
</ol>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/34.jpg"><img class="aligncenter size-medium wp-image-1048" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/02/34-300x166.jpg" alt="" width="300" height="166" /></a></p>
<p><center></center></p>
<ol type="a">
<li>The next step is to configure the DSN in the application server. Our DSN is bound to the name “jdbc/scramdleDSN” in JNDI. This is shown below in the snapshot. This DSN will use <strong>“scramblePool”</strong>created in the previous step.</li>
</ol>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/44.jpg"><img class="aligncenter size-medium wp-image-1050" title="4" src="http://www.javabeat.net/wp-content/uploads/2011/02/44-300x166.jpg" alt="" width="300" height="166" /></a></li>
</ol>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-j2ee%2Fjpa%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/java-j2ee/jpa/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/java-j2ee/jpa/feed/" data-count="vertical" data-text="JPA" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/02/struts-2-0-and-jpa-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create applications using ObjectDb and JPA in NetBeans</title>
		<link>http://www.javabeat.net/2011/02/create-applications-using-objectdb-and-jpa-in-netbeans/</link>
		<comments>http://www.javabeat.net/2011/02/create-applications-using-objectdb-and-jpa-in-netbeans/#comments</comments>
		<pubDate>Sat, 19 Feb 2011 13:21:33 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[NetBeans]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=553</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction I have been developing Java applications for a long time and the major difficulty was the coding part related to database manipulations. Recently I shifted to use Object-Relational Mapping through JPA. I have used TopLink, EclipseLink, and Hibernate. Although I could achieve the functionally I want with ease, the output was slower when compared [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>I have been developing Java applications for a long time and the major difficulty was the coding part related to database manipulations. Recently I shifted to use Object-Relational Mapping through JPA. I have used <a href="http://www.oracle.com/technetwork/middleware/toplink/index.html" target="_blank">TopLink</a>, <a href="http://www.eclipse.org/eclipselink/" target="_blank">EclipseLink</a>, and <a href="http://www.hibernate.org/" target="_blank">Hibernate</a>. Although I could achieve the functionally I want with ease, the output was slower when compared to normal method of database connection with JDBC. Then I used some Object databases like <a href="http://www.neodatis.org/" target="_blank">neoDatis</a>. They were quite faster, yet I was reluctant to proceed as most of them had their own standards and did not comply to JPA. Finally I found the <a href="http://www.objectdb.com/" target="_blank">ObjectDB</a>, an Object database for Java which completely supports JPA.</p>
<p>This article demonstrates how to create a simple JAVA Standard application in NetBeans using ObjectDB and JPA. The demonstrated application uses JPA to store and retrieve objects of two entity classes from an Embedded ObjectDB. It will demonstrate the capabilities of ObjectDB and JPA, which include persisting objects, removing saved objects and retrieving persisted objects. For this tutorial, besides the <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" target="_blank">Java JDK</a> and the <a href="http://netbeans.org/" target="_blank">NetBeans IDE</a>,you only need to <a href="http://www.objectdb.com/object/db/database/download" target="_blank">download</a><br />
and extract the <a href="http://www.objectdb.com/object/db/database/version/2-0-3-build-01" target="_blank">ObjectDB distribution zip file</a>.The distribution zip contains everything necessary without any external dependency.</p>
<h2>This tutorial consists of the following steps</h2>
<ul>
<li>Step 1: Create an ObjectDB Enabled Java SE Project</li>
<li>Step 2: Define a JPA Entity Classes</li>
<li>Step 3: Add a Main Class</li>
<li>Step 4: Design a Graphical User Interface</li>
<li>Step 5: Code user-defined Methods</li>
<li>Step 6: Code Events of Controls</li>
<li>Step 7: Run the program</li>
</ul>
<h2>Step 1: Create an ObjectDB Enabled Project</h2>
<p>We start by creating a new NetBeans Project.</p>
<p>From the menu, select <strong>File &gt; New</strong> to get the <strong>[New Project]</strong> dialog box</p>
<p>Select   <strong>Java </strong>from Categories and<strong><br />
Java Application </strong> from Projects and click  <strong>Next</strong></p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/12.jpg"><img class="aligncenter size-medium wp-image-1024" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/02/12-300x206.jpg" alt="" width="300" height="206" /></a>Choose a Project Name (e.g  <strong>City</strong></p>
<p>Set the name of the Main class to  <strong>main.Main – </strong>This will create a package named main and a Java Class named Main with the public static void main(String[] args){}</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/22.jpg"><img class="aligncenter size-medium wp-image-1025" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/02/22-300x206.jpg" alt="" width="300" height="206" /></a>Click <strong>Finish</strong> to create the project.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Then ObjectDB/JPA support has to be added to the project</p>
<p>Download the ObjectDB installation files from the <a href="http://www.objectdb.com/tutorialJPA/netbeans">download page</a>. The downloaded file, objectdb-(version).zip file has to be extracted to a folder like D:\Program Files\ObjectDB.</p>
<p>Find the project in <strong>Project window</strong>.If project window is not visible, press <strong>ctrl + 1</strong> to get the project window. Right click on the project to get the popup menu and select the Properties to get the <strong>[Project Properties]</strong> window.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/32.jpg"><img class="aligncenter size-medium wp-image-1026" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/02/32-140x300.jpg" alt="" width="140" height="300" /></a>Click on <strong>Libraries</strong> under categories of the Project Properties Window. No libraries are listed at the moment under Compile tab.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/42.jpg"><img class="aligncenter size-medium wp-image-1027" title="4" src="http://www.javabeat.net/wp-content/uploads/2011/02/42-300x218.jpg" alt="" width="300" height="218" /></a>Click on <strong>Add Jar/<span style="text-decoration: underline;">F</span>older</strong>and locate the <strong>objectdb.jar</strong> file inside the bin folder of ObjectDB extracted directory.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/5.jpg"><img class="aligncenter size-medium wp-image-1029" title="5" src="http://www.javabeat.net/wp-content/uploads/2011/02/5-300x164.jpg" alt="" width="300" height="164" /></a>This will add the objectdb.jar file to the libraries and now the project is JPA/ObjectDB enabled.</p>
<p><img class="aligncenter size-medium wp-image-1030" title="6" src="http://www.javabeat.net/wp-content/uploads/2011/02/6-300x216.jpg" alt="" width="300" height="216" /></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/02/create-applications-using-objectdb-and-jpa-in-netbeans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating JSF and JPA</title>
		<link>http://www.javabeat.net/2010/07/integrating-jsf-and-jpa/</link>
		<comments>http://www.javabeat.net/2010/07/integrating-jsf-and-jpa/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 00:22:44 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java Server Faces (JSF)]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=437</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction MVC architecture has become the default choice for developing web applications. It has become a tradition to develop web applications using multi-tier architecture and hence involving one or more Frameworks. A Framework ensures faster development cycle and guarantees the usage of proven design patterns and architecture. There are various Frameworks available for each layer; [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1>Introduction</h1>
<p>MVC architecture has become the default choice for developing web applications. It has become a tradition to develop web applications using multi-tier architecture and hence involving one or more Frameworks. A Framework ensures faster development cycle and guarantees the usage of proven design patterns and architecture. There are various Frameworks available for each layer; be it presentation tier, business tier or persistence tier.</p>
<p>The architects can decide upon the choice of the frameworks for different tier based on the requirement. This article is to demonstrate how to integrate the presentation tier using JSF with the persistence tier using JPA. <strong>JSF and JPA</strong> are two popular frameworks used to develop Java EE applications.</p>
<blockquote><p><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a title="Permanent Link to Introduction to Java Server Faces" href="http://www.javabeat.net/2007/05/introduction-to-java-server-faces/" rel="bookmark">Introduction to Java Server Faces</a></li>
<li><a title="Permanent Link to Request Processing Lifecycle phases in JSF" href="http://www.javabeat.net/2007/11/request-processing-lifecycle-phases-in-jsf/" rel="bookmark">Request Processing Lifecycle phases in JSF</a></li>
<li><a title="Permanent Link to Accessing Web Services from JSF applications" href="http://www.javabeat.net/2007/11/accessing-web-services-from-jsf-applications/" rel="bookmark">Accessing Web Services from JSF applications</a></li>
<li><a title="Permanent Link to Navigation model in JSF" href="http://www.javabeat.net/2007/11/navigation-model-in-jsf/" rel="bookmark">Navigation model in JSF</a></li>
</ul>
</blockquote>
<h1>Problem Statement</h1>
<p>In this article, a scenario of generating report on employee details is considered and has been explained with the corresponding code. The module will display the details of the particular employee chosen from a drop down list box. The application starts with a home page (Home.jsp) which has a hyperlink to the report page (EmloyeeHome.jsp). The EmployeeHome.jsp has a drop down with the employee numbers populated dynamically from the database through JPA. Upon selecting a particular employee number the details of the employee will be displayed in the same page.</p>
<h1>Raising the application</h1>
<p>Step1:</p>
<ul>
<li>Create a dynamic web application in a workspace in Eclipse</li>
<li>For using JPA, add the required project facet.</li>
<ul>
<li>Right click on the project and select properties -&gt; Project Facets. Select<br />
the checkbox for Java Persistence and click on the “further configuration<br />
available&#8230;”</li>
<li>By clicking the link “further configuration available…” “JPA Facet”<br />
window will be displayed. Click on “OK” button and come to “Project<br />
Facet window”. Click on “OK” button in “Project Facet” window. This<br />
will complete the configuration required in Eclipse IDE</li>
</ul>
</ul>
<p>Step2:</p>
<ul>
<li>The classes12.jar, hibernate-entitymanager.jar, javaee.jar, jboss-faces.jar,<br />
jsf-api.jar, jsf-impl.jar, standard.jar, jstl.jar, toplink-essentials.jar,<br />
toplink-essentials-agen.jar archive files should be added on to the project<br />
to enable JPA and JSF framework in the application. Copy these jar files<br />
into the lib folder (Project -&gt; WebContent -&gt; WEB-INF -&gt; lib)</li>
</ul>
<p>Step3:</p>
<ul>
<li>Create a Home.jsp with a hyperlink to EmployeeHome.jsp</li>
<li>Sample code (Home.jsp)</li>
</ul>
<pre class="brush: java; title: ; notranslate">
&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html;
charset=ISO-8859-1&quot; pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;%@ taglib prefix=&quot;f&quot; uri=&quot;http://java.sun.com/jsf/core&quot;%&gt;
&lt;%@ taglib prefix=&quot;h&quot; uri=&quot;http://java.sun.com/jsf/html&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
	&lt;title&gt;Home page&lt;/title&gt;
&lt;/head&gt;
  &lt;body&gt;
	&lt;f:view&gt;
		&lt;h3&gt;
		&lt;center&gt;
		&lt;h:outputLabel&gt;Welcome to the Home Page&lt;/h:outputLabel&gt;
		&lt;/center&gt;
		&lt;h:outputLink value=&quot;EmployeeHome.jsp&quot;&gt;Employee Details&lt;/h:outputLink&gt;
        	&lt;/h3&gt;
	&lt;/f:view&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>Sample Screen Shot</strong></p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2010/07/1.jpg"><img class="aligncenter size-medium wp-image-959" title="1" src="http://www.javabeat.net/wp-content/uploads/2010/07/1-300x115.jpg" alt="" width="300" height="115" /></a><br />
Step4:</p>
<ol type="a">
<ol type="a">
<li>When the <em>Employee Details</em> hyperlink is clicked, Employee Home page is displayed.</li>
<li>Create EmployeeHome.jsp</li>
<li>Sample Code (EmployeeHome.jsp)</li>
</ol>
</ol>
<pre class="brush: java; title: ; notranslate">
&lt;%@ page language=&quot;java&quot;
contentType=&quot;text/html; charset=ISO-8859-1&quot;
	pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;%@ taglib prefix=&quot;f&quot; uri=&quot;http://java.sun.com/jsf/core&quot;%&gt;
&lt;%@ taglib prefix=&quot;h&quot; uri=&quot;http://java.sun.com/jsf/html&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
	&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
	&lt;title&gt;Employee Details&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;f:view&gt;
	&lt;h3&gt;
        	&lt;center&gt;Welcome to Employee Home Page&lt;/center&gt;
	&lt;/h3&gt;
	&lt;br&gt;&lt;br&gt;
	&lt;h:form&gt;
	&lt;h3&gt;
		Select an Employee Number from the drop down:
	&lt;/h3&gt;
	&lt;br&gt;&lt;br&gt;
	&lt;h:selectOneMenu id=&quot;selEmpNo&quot;
		alueChangeListener=&quot;#{employee.employeeReport}&quot;
		onchange=&quot;submit()&quot;&gt;
		&lt;f:selectItem itemLabel=&quot;select&quot; /&gt;
	&lt;f:selectItems value=&quot;#{employee.empNoList}&quot; id=&quot;emp&quot;/&gt;
	&lt;/h:selectOneMenu&gt;
	&lt;/h:form&gt;
	&lt;br&gt;&lt;br&gt;
	&lt;h3&gt;
	&lt;h:outputText value=&quot;Employee Name: &quot;&gt;&lt;/h:outputText&gt;
	&lt;h:outputText value=&quot;#{employee.empName}&quot;/&gt;
	&lt;br&gt;&lt;br&gt;
	&lt;h:outputText value=&quot;Employee Number: &quot;/&gt;
	&lt;h:outputText value=&quot;#{employee.empNo}&quot;/&gt;
	&lt;br&gt;&lt;br&gt;
	&lt;h:outputText value=&quot;Name of the IBU: &quot;/&gt;
	&lt;h:outputText value=&quot;#{employee.ibu}&quot;/&gt;
	&lt;br&gt;&lt;br&gt;
	&lt;h:outputText value=&quot;Designation: &quot;/&gt;
	&lt;h:outputText value=&quot;#{employee.designation}&quot;/&gt;
&lt;/h3&gt;
&lt;/f:view&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<ol type="a">
<li>Sample Screen shot</li>
</ol>
<p><a href="http://www.javabeat.net/wp-content/uploads/2010/07/2.jpg"><img class="aligncenter size-medium wp-image-960" title="2" src="http://www.javabeat.net/wp-content/uploads/2010/07/2-300x99.jpg" alt="" width="300" height="99" /></a><br />
<a href="http://www.javabeat.net/wp-content/uploads/2010/07/3.jpg"><img class="aligncenter size-medium wp-image-958" title="3" src="http://www.javabeat.net/wp-content/uploads/2010/07/3-300x115.jpg" alt="" width="300" height="115" /></a><br />
<span style="text-decoration: underline;"><strong>Note:</strong></span> In EmployeeHome.jsp, &lt;f:selectItems&gt; is used to dynamically populate the<br />
drop down with employee number from the corresponding managed bean. When a particular employee number is selected from the drop down, the corresponding employee details should be displayed. In order to implement this functionality,<br />
implement ValueChangeEventListener in the corresponding managed bean and bound the UI component to it. The employeeReport(ValueChangeEvent event) of the EmployeeBean managed bean is the value change even listener in this<br />
implementation. . Since value change event will not submit the request, some mechanism (E.g., JavaScript function) is required to submit the request after selecting the employee number from the drop down. (In EmployeeHome.jsp,<br />
“submit() is assigned to “onChange” attribute of &lt;h:selectOneMenu&gt; tag. Hence no need to write any explicit java script function to submit the form.)</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Step5:</p>
<ul>
<ul>
<li>Create a package “employee” under the project</li>
<li>Create a bean EmployeeBean which is a managed bean (the configuration of the managed bean is available in faces-congig.xml file which is given latter). The attributes of this bean is bound to various UI Components used in EmployeeHome.jsp</li>
<li>Sample Code (EmployeeBean.java)</li>
</ul>
</ul>
<pre class="brush: java; title: ; notranslate">package employee;

	import java.util.ArrayList;
	import java.util.Iterator;
	import java.util.List;
	import javax.faces.event.ValueChangeEvent;
	import javax.faces.model.SelectItem;

	public class EmployeeBean {
		private String empName;
		private String ibu;
		private String designation;
		private int empNo;

		//This is used to dynamically populate the drop down with employee numbers
		List&lt;SelectItem&gt;empNoList;

		public EmployeeBean(){
			this.empNoList = new ArrayList&lt;SelectItem&gt;();
			/*Populating Employee Number in the drop down - Dynamic */
			List&lt;EmployeeEntity&gt;empList = new
				EmployeeService().getEmployeeList();
			Iterator&lt;EmployeeEntity&gt;iterator = empList.iterator();
			while(iterator.hasNext()){
				EmployeeEntity employee = iterator.next();
				SelectItem item = new SelectItem(employee.getEmpNo());
				empNoList.add(item);
			}
		}
		public String getEmpName() {
			return empName;
		}
		public void setEmpName(String empName) {
			this.empName = empName;
		}
		public String getIbu() {
			return ibu;
		}
		public void setIbu(String ibu) {
			this.ibu = ibu;
		}
		public String getDesignation() {
			return designation;
		}
		public void setDesignation(String designation) {
			this.designation = designation;
		}
		public int getEmpNo() {
			return empNo;
		}
		public void setEmpNo(int empNo) {
			this.empNo = empNo;
		}
		public List&lt;SelectItem&gt; getEmpNoList() {
			return empNoList;
		}
		public void setEmpNoList(List&lt;SelectItem&gt; empNoList) {
			this.empNoList = empNoList;
		}
		public List&lt;EmployeeEntity&gt; getEmpList() {
			return empList;
		}
		public void setEmpList(List&lt;EmployeeEntity&gt; empList) {
			this.empList = empList;
		}
		/*Eventlistener - for fetching an employee record based on the selection of employee
			number from the drop down*/
		public void employeeReport(ValueChangeEvent event){
			int empNo = Integer.parseInt((String)event.getNewValue());
			EmployeeEntity employee = new
				EmployeeService().getEmployee(empNo);
			this.empNo = employee.getEmpNo();
			this.empName = employee.getEmpName();
			this.ibu = employee.getIbu();
			this.designation = employee.getDesignation();
		}
	}
</pre>
<p><span style="text-decoration: underline;"><strong>Note:</strong></span> After selecting the employee number from the drop down, to fetch the data from the table, a service class called “EmployeeService” (code is given later) is used which makes use of JPA to fetch the required record from the<br />
table.</p>
<p>Step6:</p>
<ol type="a">
<ol type="a">
<li>Inside the package “employee”, create an entity class called “EmployeeEntity.java” which is mapped to an “employee” table</li>
<li>Sample Code (EmployeeEntity.java)</li>
</ol>
</ol>
<pre class="brush: java; title: ; notranslate">package employe;
	import javax.persistence.Entity;
	import javax.persistence.Id;
	import javax.persistence.Table;

	@Entity
	@Table(name=&quot;employee&quot;)
	public class EmployeeEntity {
		@Id
		private int empNo;
		private String empName;
		private String ibu;
		private String designation;
		public int getEmpNo() {
			return empNo;
		}
		public void setEmpNo(int empNo) {
			this.empNo = empNo;
		}
		public String getEmpName() {
			return empName;
		}
		public void setEmpName(String empName) {
			this.empName = empName;
		}
		public String getIbu() {
			return ibu;
		}
		public void setIbu(String ibu) {
			this.ibu = ibu;
		}
		public String getDesignation() {
			return designation;
		}
		public void setDesignation(String designation) {
			this.designation = designation;
		}
	}
</pre>
<p>Step7:</p>
<ol type="a">
<ol type="a">
<li>Inside the package “employee”, create a class called “EmployeeService.java”. This class will interact with the database to fetch the required details</li>
<li>Sample Code (EmployeeService.java)</li>
</ol>
</ol>
<pre class="brush: java; title: ; notranslate">package employee;
	import java.util.ArrayList;
	import java.util.List;
	import javax.persistence.EntityManager;
	import javax.persistence.EntityManagerFactory;
	import javax.persistence.EntityTransaction;
	import javax.persistence.Persistence;
	import javax.persistence.Query;

	public class EmployeeService {
		public List&lt;EmployeeEntity&gt; getEmployeeList(){
			List&lt;EmployeeEntity&gt; empList = new ArrayList&lt;EmployeeEntity&gt;();
			EntityManager em = null;
			try{
				EntityManagerFactory emf =
						Persistence.createEntityManagerFactory(&quot;Employee-
						Details&quot;);
				em = emf.createEntityManager();
				EntityTransaction et = em.getTransaction();
				et.begin();
				Query query = em.createQuery(&quot;select e from EmployeeEntitye&quot;);
				empList = query.getResultList();
			}
			catch(Exception e){
				//log the exception
			}
			return empList;
		}
		public EmployeeEntity getEmployee(int empNo){
			EmployeeEntity employee = new EmployeeEntity();
			EntityManager em = null;
			try{
				EntityManagerFactory emf =
					Persistence.createEntityManagerFactory(&quot;Employee-
					Details&quot;);
				em = emf.createEntityManager();
				EntityTransaction et = em.getTransaction();
				employee = em.find(myPackage.EmployeeEntity.class, empNo);
			}
			catch(Exception e){
				//log the exception
			}
			finally{
				if( em != null){
					em.clear();
				}
			}
			return employee;
		}
	}
</pre>
<p>Step8:</p>
<ol type="a">
<ol type="a">
<li>Create “persistence.xml” file and keep it inside META-INF folder</li>
<li>Sample Code (persistence.xml)</li>
</ol>
</ol>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;persistence version=&quot;1.0&quot; xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;
		xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
		xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence

http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;&gt;

		&lt;persistence-unit name=&quot;Employee-Details&quot;&gt;
			&lt;provider&gt;oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider&lt;/provider&gt;
			&lt;class&gt;.EmployeeEntity&lt;/class&gt;
			&lt;properties&gt;
				&lt;property name=&quot;toplink.jdbc.url&quot; value=&quot;
					jdbc:oracle:thin:@localhost:1521:nr&quot;/&gt;
				&lt;property name=&quot;toplink.jdbc.user&quot; value=&quot;scott&quot;/&gt;
				&lt;property name=&quot;toplink.jdbc.driver&quot;
					value=&quot;oracle.jdbc.driver.OracleDriver&quot;/&gt;
				&lt;property name=&quot;toplink.jdbc.password&quot; value=&quot;tiger&quot;/&gt;
				&lt;property name=&quot;toplink.ddl-generation&quot; value=&quot;update-tables&quot;/&gt;
			&lt;/properties&gt;
		&lt;/persistence-unit&gt;
&lt;/persistence&gt;</pre>
<p><span style="text-decoration: underline;"><strong>Note:</strong></span> Persistence.xml file is configured for Oracle database. You have to<br />
configure according to the database which you want to use and give the<br />
values accordingly.</p>
<p>Step9:</p>
<ol type="a">
<ol type="a">
<ol type="a">
<li>Create “faces-congig.xml” file which contains information about<br />
navigation rule and managed bean. Place the file inside WEB-INF<br />
folder</li>
<li>Sample Code (faces-config.xml)</li>
</ol>
</ol>
</ol>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;faces-config
		xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
		xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
		xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd&quot;

			version=&quot;1.2&quot;&gt;
		&lt;navigation-rule&gt;
			&lt;from-view-id&gt;/Home.jsp&lt;/from-view-id&gt;
		&lt;/navigation-rule&gt;
		&lt;managed-bean&gt;
			&lt;managed-bean-name&gt;employee&lt;/managed-bean-name&gt;
			&lt;managed-bean-class&gt;employee.EmployeeBean
			&lt;/managed-bean-class&gt;
			&lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt;
		&lt;/managed-bean&gt;
	&lt;/faces-config&gt;</pre>
<h1>Conclusion</h1>
<p>This article demonstrates how to integrate <strong>JSF and JPA</strong> while developing a web application. Apart from this, the article also illustrates how to use drop down (dynamic) in a JSF enabled JSP and how to make use of value change event listener.</p>
<h1>Acknowledgement</h1>
<p>I would like to thank my manager Mr. Rajagopalan P, Principal, Education and Research Department, Infosys for the guidance and continuous support. I would like to thank Mr. Satheesha B N, Associate Vice-President, Education<br />
and Research Department, Infosys for motivating me to write this article. I would like to thank Mrs. Yuvarani, Lead, Education and Research Department, Infosys for giving valuable suggestions.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/07/integrating-jsf-and-jpa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JPA and NetBeans</title>
		<link>http://www.javabeat.net/2008/07/jpa-in-netbeans-6-1/</link>
		<comments>http://www.javabeat.net/2008/07/jpa-in-netbeans-6-1/#comments</comments>
		<pubDate>Mon, 28 Jul 2008 13:04:04 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JPA]]></category>
		<category><![CDATA[NetBeans]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=197</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this article we will see how to use Java Persistence API (JPA) in NetBeans 6.1 with in a Java application. The JPA was first introduced as part of the Java EE 5 platform. This article will not provide any of the theoretical information about JPA. Software used NetBeans IDE 6.1 JDK version 5.0/6.0 MySql [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><span style="font-size: 13px;">In this article we will see how to use </span><b style="font-size: 13px;"><i>Java Persistence API (JPA)</i></b><span style="font-size: 13px;"> in </span><b style="font-size: 13px;"><i>NetBeans 6.1</i></b><span style="font-size: 13px;"> with in a Java application. The </span><b style="font-size: 13px;"><i>JPA</i></b><span style="font-size: 13px;"> was first introduced as part of the Java EE 5 platform. This article will not provide any of the theoretical information about </span><b style="font-size: 13px;"><i>JPA</i></b><span style="font-size: 13px;">.</span></p>
<h2>Software used</h2>
<ul>
<li><b><i>NetBeans IDE 6.1</i></b></li>
<li><b><i>JDK version 5.0/6.0</i></b></li>
<li><b><i>MySql 5.0</i></b></li>
</ul>
<h2>Creating a database in MySql 5.0</h2>
<p>To start with first of all we will have to create a database in <b><i>MySql</i></b>. Let us name the database as “jpaDB”. To create a database we will execute the following in the mysql command line prompt.</p>
<pre class="brush: java; title: ; notranslate">
CREATE DATABASE jpaDB;

GRANT ALL ON jpaDB.* TO jpaDB@&quot;%&quot; IDENTIFIED BY &quot;jpaDB&quot;;
GRANT ALL ON jpaDB.* TO jpaDB@&quot;localhost&quot; IDENTIFIED BY &quot;jpaDB&quot;;

USE jpaDB;       </pre>
<p style="text-align: center;">
<a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-1.png"><img class="aligncenter  wp-image-6743" alt="jpa-1" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-1.png" width="474" height="211" /></a></p>
<h2>Set up a connection to a MySQL database from NetBeans IDE 6.1</h2>
<p><b><i>NetBeans IDE 6.1</i></b> comes with support for the MySQL database. To set up MySql properly in <b><i>Netbeans IDE 6.1</i></b> follow the steps below.</p>
<ul>
<ul>
<li>1. In Services window expand Databases node. See the screen shot below.</li>
</ul>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-2.png"><img class="aligncenter size-full wp-image-6744" alt="jpa-2" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-2.png" width="402" height="231" /></a></p>
<ul>
<ul>
<li>2. Right click on <b><i>MySQL</i></b> server node. <b><i>MySQL</i></b> Server Properties dialog window opens.</li>
</ul>
</ul>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-3.png"><img class="aligncenter  wp-image-6745" alt="jpa-3" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-3.png" width="456" height="269" /></a></p>
<ul>
<ul>
<li>3. Already host name, port number and admin user name will be pre populated in the dialog. If not then fill in properties and click on ok.</li>
</ul>
</ul>
<p><i>Note: Before you can connect to a <b><i>MySQL</i></b> Database Server, you must first ensure that the <b><i>MySQL Database Server</i></b> is running on your machine. The <b><i>MySQL</i></b> Server node in the Service indicates whether the MySQL Database Server is connected, as shown in the following image.</i></p>
<ul>
<ul>
<li>4. After starting the Database Server on your machine, start the MySQL Database Server in the IDE by right-clicking the MySQL Server node and choosing Start.</li>
<li>5. Now expand the <b><i>MySQL</i></b> server node. We can see the database which we created using command prompt. (We also can create the database using netbeans itself. Since we have created the database already we don’t cover those steps in this artical).</li>
</ul>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-4.png"><img class="aligncenter size-full wp-image-6746" alt="jpa-4" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-4.png" width="400" height="255" /></a></p>
<ul>
<ul>
<li>6. Now we will connect the database as shown below in the figure. Enter the password for the user if there is one, then click OK to create the new database connection. Click OK again if no schema is required.</li>
</ul>
</ul>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-5.png"><img class="aligncenter  wp-image-6747" alt="jpa-5" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-5.png" width="421" height="288" /></a></p>
<ul>
<li>7. we can see the database appearing in the services window.</li>
</ul>
<h2>Creating Table in MySql 5.0</h2>
<p>Now we will create a table and name it as &#8220;USER&#8221;.<br />
In the services window expand the database (See the figure below)<br />
we created in the previous section. Right click on the table node.<br />
select create table.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-6.png"><img class="aligncenter size-full wp-image-6748" alt="jpa-6" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-6.png" width="402" height="241" /></a></p>
<p>Invoking on create table node will result in create table dialog.<br />
This window will halp us in creating the table with ease as shown in the below diagram.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-7.png"><img class="aligncenter  wp-image-6749" alt="jpa-7" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-7.png" width="465" height="239" /></a><br />
<a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-8.png"><img class="aligncenter size-full wp-image-6750" alt="jpa-8" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-8.png" width="354" height="210" /></a></p>
<h2>Create a JavaApplication in NetBeans 6.1</h2>
<p>Now create a java application in <b><i>NetBeans IDE</i></b>. Let us name the application as MyJPAApplication.</p>
<p>Next step is to generate a Entity class which will map to User table.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-9.png"><img class="aligncenter  wp-image-6751" alt="jpa-9" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-9.png" width="366" height="251" /></a></p>
<p>Select the database created as shown in the below figure.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-10.png"><img class="aligncenter  wp-image-6752" alt="jpa-10" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-10.png" width="473" height="312" /></a></p>
<p>You can now see the tables available in the database will be listed in the Available Tables menu.<br />
Select the user table and click on Add to move it to Selected tables menu.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-11.png"><img class="aligncenter  wp-image-6753" alt="jpa-11" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-11.png" width="473" height="312" /></a></p>
<p>Change the class name in the next wizard as UserGenEntity. Then click on Create Persistence Unit button.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-12.png"><img class="aligncenter  wp-image-6754" alt="jpa-12" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-12.png" width="473" height="312" /></a></p>
<p>In the create persistant unit wizard, change the Table Generation Strategy option to Create.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-13.png"><img class="aligncenter size-full wp-image-6755" alt="jpa-13" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-13.png" width="512" height="251" /></a></p>
<p>Now in the final wizard there will not be any information or warning messages shown. Then click on finish.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-14.png"><img class="aligncenter  wp-image-6756" alt="jpa-14" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-14.png" width="473" height="312" /></a></p>
<p>Once you clicked on finish. you can see the class named UserGenEntity getting generated in the Projects window of the IDE. You can also see the TopLink libraries getting added to the Libraries node as shown below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-15.png"><img class="aligncenter size-full wp-image-6757" alt="jpa-15" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-15.png" width="381" height="426" /></a></p>
<p>Next step is to implement a Manager Class which handles the <b><i>JPA persistence-context</i></b>. That means this class is responsible to provide <b><i>CRUD</i></b> functionality for your instances and to communicate with your database.<br />
We will name this manager class as UserManager. UserManager code is given in the below listing.</p>
<h2>Sample JPA Application</h2>
<pre class="brush: java; title: ; notranslate">
package com.myJpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

/**
 *
 * @author Sri hari
 */
public class UserManager {

    private EntityManager em;

    public UserManager(EntityManagerFactory emf) {
        em = emf.createEntityManager();
    }

    public void createUser(UserGenEntity user) {
        em.getTransaction().begin();
        em.persist(user);
        em.getTransaction().commit();
    }

    public UserGenEntity searchById(Integer id) {
        return em.find(UserGenEntity.class, id);
    }

    public void updateUser(UserGenEntity user) {
        em.getTransaction().begin();
        em.merge(user);
        em.getTransaction().commit();
    }

    public void removeUser(UserGenEntity user) {
        em.getTransaction().begin();
        em.remove(user);
        em.getTransaction().commit();
    }

    public List getAll() {
        Query query = em.createQuery(&quot;select a from UserGenEntity a&quot;);
        List list = query.getResultList();
        return list;
    }

    public void close() {
        em.close();
    }
}
        </pre>
<p>Code List has the following methods:</p>
<ul>
<li>createUser &#8212; this method is used to create a user in the database.</li>
<li>searchById &#8212; this method is used to search a user by ID.</li>
<li>updateUser &#8212; this method is used to update a user from the table.</li>
<li>removeUser &#8212; this method is used to remove a user from the table.</li>
<li>getAll &#8212; this method is used to get all the users from the table.</li>
</ul>
<h2>Testing the JPA code</h2>
<p>Now its time to test the code and see how it works. Before that don&#8217;t forget to add the driver for MySQL to your project library.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-16.png"><img class="aligncenter size-full wp-image-6758" alt="jpa-16" src="http://www.javabeat.net/wp-content/uploads/2008/07/jpa-16.png" width="372" height="401" /></a></p>
<p>Testing can be done using JUnit or a simple Java class with main method. Here we will create a simple java class with main method to test our code.</p>
<pre class="brush: java; title: ; notranslate">
package com.myJpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Sri hari
 */
public class TestJPA {

    private UserManager um;
    private EntityManager em;
    private EntityManagerFactory emf;
    private static final UserGenEntity user1 = new UserGenEntity(1, &quot;Muthu&quot;, &quot;Dhanagopal&quot;);
    private static final UserGenEntity user2 = new UserGenEntity(2, &quot;Sri&quot;, &quot;Hari&quot;);

    protected void setUp() throws Exception {
        emf = Persistence.createEntityManagerFactory(&quot;MyJPAApplicationPU&quot;);
        em = emf.createEntityManager();
        um = new UserManager(emf);
    }

    protected void close() throws Exception {
        um.close();
        em.close();
        emf.close();
    }

    public void test() {
        um.createUser(user1);
        UserGenEntity user = um.searchById(1);
        System.out.println(&quot;After creation of user in table&quot;);
        System.out.println(&quot;Firstname: &quot; + user.getFirstname());
        System.out.println(&quot;Lastname: &quot; + user.getLastname());

        user.setFirstname(&quot;Muthukumar&quot;);
        um.updateUser(user);

        user = um.searchById(1);
        System.out.println(&quot;After update.&quot;);
        System.out.println(&quot;Firstname: &quot; + user.getFirstname());
        System.out.println(&quot;Lastname: &quot; + user.getLastname());

        System.out.println(&quot;Adding one more record&quot;);
        um.createUser(user2);

        List list = um.getAll();
        System.out.println(&quot;Number of users: &quot; + list.size());
    }

    public static void main(String args[]) {
        System.out.println(&quot;Inside TestJPA main&quot;);
        TestJPA testJPA = new TestJPA();
        try {
            testJPA.setUp();
            testJPA.test();
            testJPA.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(&quot;End of TestJPA main&quot;);
    }
}
        </pre>
<h2>Result</h2>
<pre class="brush: java; title: ; notranslate">
init:
deps-jar:
compile-single:
run-single:
Inside TestJPA main
[TopLink Info]: 2008.07.27 09:42:50.500--ServerSession(16602326)--TopLink, version: Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))
[TopLink Info]: 2008.07.27 09:42:52.253--ServerSession(16602326)--file:/C:/NetBeansProjects/MyJPAApplication/build/classes/-MyJPAApplicationPU login successful
[TopLink Warning]: 2008.07.27 09:42:52.410--ServerSession(16602326)--Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'user' already exists
Error Code: 1050
Call: CREATE TABLE user (ID INTEGER NOT NULL, FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), PRIMARY KEY (ID))
Query: DataModifyQuery()
After creation of user in table
Firstname: Muthu
Lastname: Dhanagopal
After update.
Firstname: Muthukumar
Lastname: Dhanagopal
Adding one more record
Number of users: 2
[TopLink Info]: 2008.07.27 09:42:52.864--ServerSession(16602326)--file:/C:/NetBeansProjects/MyJPAApplication/build/classes/-MyJPAApplicationPU logout successful
End of TestJPA main
BUILD SUCCESSFUL (total time: 7 seconds)</pre>
<h2>Summary</h2>
<p>In this article you have learnt how to develop a JPA persistence layer using Java Application. This is not the end, Still miles to go.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/07/jpa-in-netbeans-6-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sample Application for Java Persistence API (JPA)</title>
		<link>http://www.javabeat.net/2007/04/sample-application-for-java-persistence-api-jpa/</link>
		<comments>http://www.javabeat.net/2007/04/sample-application-for-java-persistence-api-jpa/#comments</comments>
		<pubDate>Sun, 15 Apr 2007 13:17:44 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JPA]]></category>
		<category><![CDATA[Java Persistence API (JPA)]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3886</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is the last part of the article series Java Persistence API (JPA), the earlier articles are introduction to JPA and the query api in JPA. This article is only for explaining the sample program with concepts used in the previous articles. I would recommend reading the previous two articles before start analyzing this [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>This article is the last part of the article series <strong>Java Persistence API (JPA)</strong>, the earlier articles are <a href="http://www.javabeat.net/2007/04/jpa/">introduction to JPA</a> and <a href="http://www.javabeat.net/2007/04/the-query-api-in-jpa-ejb-3-0/">the query api in JPA</a>. This article is only for explaining the sample program with concepts used in the previous articles. I would recommend reading the previous two articles before start analyzing this sample code. If you are familiar with the <strong>JPA</strong> concepts, you can jump into the code and complete reading this article. If you have any doubts or queries, please post it in the comments section. Thank you for reading our blog. Have a fun!!</p>
<p>Following is a sample code in J2SE that creates and find Employee objects.</p>
<p><strong>Code for Employee.java</strong></p>
<pre class="brush: java; title: ; notranslate">package com.javabeat.ejb30.persistence.entities;

	import java.io.Serializable;
	import javax.persistence.Column;
	import javax.persistence.Entity;
	import javax.persistence.GeneratedValue;
	import javax.persistence.GenerationType;
	import javax.persistence.Id;
	import javax.persistence.NamedQueries;
	import javax.persistence.NamedQuery;

	@Entity(name = &quot;EMPLOYEE&quot;)

	@NamedQueries({
		@NamedQuery(name = &quot;Employee.findAll&quot;,
                query = &quot;SELECT EMP FROM EMPLOYEE AS EMP&quot;)
	})

	public class Employee implements Serializable {

		@Column(name = &quot;EMP_NAME&quot;, nullable = false, length = 100)
		private String name;

		@Column(name = &quot;EMP_AGE&quot;, nullable = true)
		private int age;

		@Column(name = &quot;EMP_SALARY&quot;, nullable = true)
		private double salary;

		@Id
		@Column(name = &quot;EMP_ID&quot;, nullable = false)
		private Long id;

		public Employee() {
		}

		public String getName(){
			return name;
		}

		public void setName(String name){
			this.name = name;
		}

		public int getAge(){
			return age;
		}

		public void setAge(int age){
			this.age = age;
		}

		public double getSalary(){
			return salary;
		}

		public void setSalary(double salary){
			this.salary = salary;
		}
		public Long getId() {
			return this.id;
		}

		public void setId(Long id) {
			this.id = id;
		}
	}</pre>
<p>The following code test the Employee entity class by creating some sample employee objects and then finding them using the <strong>Query API.</strong></p>
<p><strong>Code for EmployeeTest.java:</strong></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">package employee.test;

	import com.javabeat.ejb30.persistence.entities.Employee;
	import java.util.Arrays;
	import java.util.List;
	import javax.naming.Name;
	import javax.persistence.EntityManager;
	import javax.persistence.EntityManagerFactory;
	import javax.persistence.Persistence;
	import javax.persistence.Query;

	public class EmployeeTest {

		private static EntityManagerFactory entityManagerFactory =
	     Persistence.createEntityManagerFactory(&quot;EmployeePersistentUnit&quot;);

		private EntityManager entityManager;

		public EmployeeTest() {
			entityManager = entityManagerFactory.createEntityManager();
		}

		public void createEmployees(){
			try{
				beginTransaction();
				Employee emp1 = createEmployee(&quot;Johny&quot;, 35, 10000, 1L);
				entityManager.persist(emp1);
				Employee emp2 = createEmployee(&quot;David&quot;, 43, 50000, 2L);
				entityManager.persist(emp2);
				Employee emp3 = createEmployee(&quot;Philip&quot;, 55, 70000, 3L);
				entityManager.persist(emp3);
				Employee emp4 = createEmployee(&quot;James&quot;, 29, 30000, 4L);
				entityManager.persist(emp4);
			}catch (Exception exception){
				failTransaction();
			}finally{
				commitTransaction();
			}
		}

		public List findAllEmployees(){
			Query query = entityManager.createNamedQuery(&quot;Employee.findAll&quot;);
			List employees = query.getResultList();
			return ((List)employees);
		}

		public Employee findByName(String empName){
			String queryString =
	&quot;SELECT EMP FROM EMPLOYEE AS EMP WHERE EMP.EMP_NAME = ?1&quot;;
			Query query = entityManager.createQuery(queryString);
			query.setParameter(1, empName);
			return (Employee)query.getSingleResult();
		}

		public void display(List employees){
			for(Employee employee : employees){
				display(employee);
			}
		}

		private void display(Employee employee){
			StringBuilder results = new StringBuilder();
	results.append(&quot;Name = &quot; + employee.getName() + &quot;, Age = &quot;
                     + employee.getAge() + &quot;, &quot;);
	results.append(&quot;Salary = &quot; + employee.getSalary() + &quot;,
                     Id = &quot; + employee.getId());
			System.out.println(results.toString());
		}

		private void beginTransaction(){
			entityManager.getTransaction().begin();
		}

		private void commitTransaction(){
			entityManager.getTransaction().commit();
		}

		private void failTransaction(){
			entityManager.getTransaction().rollback();
		}

		private Employee createEmployee(String name, int age,
                         double salary, long primaryKey){
			Employee employee = new Employee();
			employee.setName(name);
			employee.setAge(age);
			employee.setSalary(salary);
			employee.setId(primaryKey);
			return employee;
		}
	}</pre>
<p>For the above code to work, we have to create a persistence.xml file that contains the configurations for the EntityManager object like the database name, its URL, username/password etc inside the META-INF directory. Since it is a J2SE application we have to declare the type of transaction as Resource-Local. The following is the persistence.xml</p>
<p><strong>Persistence.xml file:</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;persistence&gt;
	&lt;persistence-unit name=&quot;EmployeePersistentUnit&quot;
         transaction-type=&quot;RESOURCE_LOCAL&quot;&gt;
                &lt;provider&gt;oracle.toplink.essentials.
               ejb.cmp3.EntityManagerFactoryProvider&lt;/provide&gt;
		&lt;class&gt;
                    com.javabeat.ejb30.persistence.entities.Employee
                &lt;/class&gt;
		&lt;properties&gt;
		  vproperty
	name=&quot;toplink.jdbc.url&quot; value=&quot;jdbc:derby://localhost:1527/sample&quot;/&gt;
		  &lt;property
	name=&quot;toplink.jdbc.user&quot; value=&quot;app&quot;/&gt;
	 &lt;property
	name=&quot;toplink.jdbc.driver&quot; value=&quot;org.apache.derby.jdbc.ClientDriver&quot;/&gt;
		  &lt;property name=&quot;toplink.jdbc.password&quot; value=&quot;app&quot;/&gt;
		  &lt;property name=&quot;toplink.ddl-generation&quot;
                   value=&quot;drop-and-create-tables&quot;/&gt;
		&lt;/properties&gt;
	  &lt;/persistence-unit&gt;
	&lt;/persistence&gt;</pre>
<p>The above example uses the apache derby database for persisting the Employee objects as represented by the provider tag.</p>
<blockquote><p><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a href="http://www.javabeat.net/2007/04/jpa/">Introduction to JPA</a></li>
<li><a href="http://www.javabeat.net/2007/04/the-query-api-in-jpa-ejb-3-0/">The query api in JPA</a>.</li>
</ul>
</blockquote>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/04/sample-application-for-java-persistence-api-jpa/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The Query API in JPA (EJB 3.0)</title>
		<link>http://www.javabeat.net/2007/04/the-query-api-in-jpa-ejb-3-0/</link>
		<comments>http://www.javabeat.net/2007/04/the-query-api-in-jpa-ejb-3-0/#comments</comments>
		<pubDate>Sat, 14 Apr 2007 13:16:29 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JPA]]></category>
		<category><![CDATA[Java Persistence API (JPA)]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3885</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction One of the disadvantage of locating the entity objects using the EntityManager.find() and EntityManager.getReference() methods is, we cannot specify any powerful search criteria for searching the entity objects. All we can provide is the primary key to request for a particular object. Another fact is the class name of entity must be known. The [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>One of the disadvantage of locating the entity objects using the EntityManager.find() and EntityManager.getReference() methods is, we cannot specify any powerful search criteria for searching the entity objects. All we can provide is the primary key to request for a particular object. Another fact is the class name of entity must be known. The Query API that comes with JPA is powerful in the sense more additional criteria can be specified in the run-time during executing the query.</p>
<p>EntityManager serves as factory classes for getting a reference to the Query objects. The query string that we specify for locating entity objects is called Java Persistent Query Language (JPQL). The current version of the JPQL is 1.0 and it is more robust flexible and object-oriented than SQL. The persistence engine will parse the query string, transform the JPQL to the native SQL before executing it.</p>
<blockquote><p><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a href="http://www.javabeat.net/2007/04/jpa/">Introduction to JPA</a></li>
<li><a href="http://www.javabeat.net/2007/04/sample-application-for-java-persistence-api-jpa/">Sample Application Using JPA</a></li>
</ul>
</blockquote>
<h2>Types of Queries</h2>
<p>Queries can be classified into two different types depending upon how actually the query string is defined. One is the static query (Named Query) and the other one, the Dynamic Query.</p>
<h3>Static Query</h3>
<p>A static query (or a named query) is one which is defined statically with the help of annotation (or XML) before the entity class. A name is usually given to the query definition so that other components in the same persistent unit can refer the query using the same.</p>
<p>For example,</p>
<pre class="brush: java; title: ; notranslate">
@NamedQuery(name = &quot;MobileEntity.findAll&quot;
                  query = “SELECT M FROM MOBILEENTITY”)
	@Entity
	class MobileEntity{
	}</pre>
<p>A named query (with a name ‘Mobile.findAll’) has been defined and this query can be referenced later in the code through its name, like this.</p>
<pre class="brush: java; title: ; notranslate">Query findAllQuery = entityManager.createNamedQuery
               (&quot;MobileEntity.findAll&quot;);
	// Execute the query.</pre>
<p>Note that the code is referring the query by its name (‘Mobile.findAll’) by calling the createNamedQuery() method. Also, since these named queries are statically defined, during deployment time itself, the persistent engine may parse and translate the JPQL into native SQL, cache them, thereby yielding better performance.</p>
<p>Multiple named queries can be logically defined with the help of @NamedQueries, like this,</p>
<pre class="brush: java; title: ; notranslate">@NamedQueries( {
	@NamedQuery(name = &quot;Mobile.selectAllQuery&quot;
                query = &quot;SELECT M FROM MOBILEENTITY&quot;),

		@NamedQuery(name = &quot;Mobile.deleteAllQuery&quot;
         query = &quot;DELETE M FROM MOBILEENTITY&quot;)
	} )</pre>
<p>[The @NamedQueries is very similar like @NamedQuery, but can accept multiple @NamedQuery objects, The definition of the @NamedQueries looks like this,</p>
<pre class="brush: java; title: ; notranslate">@interface NamedQuries{
		NamedQuery[] value;
	}</pre>
<p>The way to specify arrayed elements with the definition of an annotation is by using {}. So was defined for the @NamedQueries( {…} ) and since the property called ‘value’ is the default property name for annotation, there is no need to explicitly mention the property name in the annotation definition. Following also works well which explicitly defines the property name ‘value’ for the annotation @NamedQueries.</p>
<pre class="brush: java; title: ; notranslate">@NamedQueries(value = { …. } )</pre>
<h3>Dynamic Queries</h3>
<p>Dynamic Queries are nothing but whose query strings are provided at run-time. All calls to EntityManager.createQuery(queryString) are actually creating dynamic query objects. By defining query objects in this way, we lose the efficiency and from the performance point of view, the query execution may be slow as the persistence engine has to do all the parsing and validation stuffs, along with mapping the JPQL to the SQL at the run-time.</p>
<p>Following code creates a dynamic query object on the fly.</p>
<pre class="brush: java; title: ; notranslate">String queryString = …… // Obtained during run-time.
	Query dynaQuery = entityManager.createQuery(queryString);</pre>
<p>Static Queries will be a better choice if the scenario for which the query to be executed is well known in advance.</p>
<h2>Query Operations</h2>
<p>Subsequent topics cover how to work with the query API for locating the entity objects, named and the positional support for Query objects and Paging Query Results for performance.</p>
<h3>Single Result</h3>
<p>The following code shows how to execute a query that returns a single entity object (assuming that a table called MobileEntity with field’s model, manufacturer and imei are available in the database).</p>
<pre class="brush: java; title: ; notranslate">Query singleSelectQuery = entityManager.createQuery(
	&quot;SELECT M FROM MOBILEENTITY WHERE M.IMEI = 'ABC-123'&quot;);
	MobileEntity mobileObj = singleSelectQuery.getSingleResult();</pre>
<p>The query string that’s defined inside the createQuery() method is the Java Persistence Query Language. The Java Persistent Query Language (JPQL) resembles more like a SQL. The query statement is a simple select statement that is used to select a particular mobile object with imeiNo ‘ABC-123’. M represents a named instance row, which can be used to directly refer the fields in the corresponding table.</p>
<p>A call to getSingleResult() will execute the query and returns a single row that matches the search criteria in the query string. If the match wasn’t successful, then the getSingleResult() will return an EntityNotFoundException. Also, if more than one matches occur during query execution (this may not happen in our case, since imeiNo is a primary key), a run-time NonUniqueResultException will be thrown.</p>
<h3>Multiple Results</h3>
<p>Query.getResultList() will execute a query and may return a List object containing multiple entity instances. The following code demonstrates the same.</p>
<pre class="brush: java; title: ; notranslate">Query multipleSelect = entityManager
                .createQuery(&quot;SELECT M FROM MOBILE&quot;);
	List mobiles =
	(List)multipleSelect.getResultList();</pre>
<p>The type-cast (List) is necessary as the getResultList() method will return a non-parameterized List object. If only one mobile object is found as a result of executing the query, then this method may simple return a list with size 1. Also note that, getResultList() method can only execute on select statements as opposed to UPDATE or DELETE statements. If any statement other than SELECT statement is passed on to the method, then an IllegalStateException will be thrown at the run-time.</p>
<h3>Working with parameters</h3>
<p>To reuse and to execute the query more efficiently with different set of values, one can depend on the parameter support (positional and named) offered by the JPA. These techniques resembles the one we had for the java.sql.PreparedStatement where one can prepare the statement object once and can execute the query with different set of parameter values again and again.</p>
<p>The positional parameter is used to bind the parameter value in terms of positional index and it is denoted by ?index within the query string. Similarly the named parameter is used to substitute the parameter value which is specified in terms of :name.</p>
<p>Following examples will clarify the above concepts,</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">String selectQuery =
	“SELECT M FROM MOBILE WHERE M.MODEL = ?1 and M.MANUFACTURER = ?2”;
	Query selectQuery = entityManager.createQuery(selectQuery);

	selectQuery.setParameter(1, model);
	selectQuery.setParameter(2, manufacturer);</pre>
<p>The above code illustrates the positional parameter support, during query execution,?1 and ?2 will be replaced with the values specified for model and manufacturer.</p>
<p>For named parameter, the parameter can be given with some meaningful name prefixed with :, like the below code,</p>
<pre class="brush: java; title: ; notranslate">String selectQuery = &quot;SELECT M FROM MOBILE WHERE M.MODEL =
                 :modelName and M.MANUFACTURER = :manufacturer&quot;;
	Query selectQuery = entityManager.createQuery(selectQuery);

	selectQuery.setParameter(“modelName”, model);
	selectQuery.setParameter(“manufacturer”, manufacturer);</pre>
<p>It is not that only dynamic queries can be benefited with positional and named parameters. Even for statically defined queries, the same is applicable. We can embed : or ? even in the static query definitions also,</p>
<pre class="brush: java; title: ; notranslate">@NamedQuery(
	name =
	&quot;Mobile.findByModel” query = &quot;SELECT M FROM MOBILEENTITY WHERE
                    M.MODEL  = :modelName
	)
	…</pre>
<p>And later in code,</p>
<pre class="brush: java; title: ; notranslate">Query namedQuery = entityManager.createNamedQuery(&quot;Mobile.findByModel&quot;);
	namedQuery.setParameter(&quot;modelName&quot;, model);</pre>
<h3>Paging Query Results</h3>
<p>Imagine that a select query is returning larger number of record entities, it may not be advisable to show the entire set of results to the end-user as it may eat performance. The following two methods can be used in tandem to solve this kind of performance issue.</p>
<p>Assume that we have 1000 mobile entities in our database and we wish to show only 100 objects in an application that displays them in a nice tabular view. In the following code, before calling the getResultList(), which will return all the mobile objects in the database, the query object is well configured with setMaxResults(maxResults) method (the number of maximum entity objects that will be returned) setFirstPosition(position) method (which tells starting position of the pointer is made to point to).</p>
<pre class="brush: java; title: ; notranslate">int maxRecords = 10;
	int startPosition = 0;
	String queryString = “SELECT M FROM MOBILEENTITY”;

	while(true){

		Query selectQuery = entityManager.createQuery(queryString);
		selectQuery.setMaxResults(maxRecords);
		selectQuery.setFirstResult(startPosition);
		List mobiles = entityManager.getResultList(queryString);

		if (mobiles.isEmpty()){
			break;
		}

	//Process the mobile entities.
	process(mobiles);
	entityManager.clear();

	startPosition = startPosition + mobiles.size();
	}</pre>
<p>The above code loops through all the 100 objects in the database in a more efficient way. Also note that the EntityManager.clear() method is called every time, to clear (or to detach) the mobile objects which will make the EntityManager less burdened in terms of managing the mobile objects.</p>
<h3>Flushing Query objects</h3>
<p>JPA provides two modes of flushing query objects namely AUTO and COMMIT (which are defined in FlushModeType Enumeration). If the AUTO mode is set on the Query object which is the default one, then any changes made to entity objects will be reflected the very next time when a select query is made. That means that the persistence engine must make sure to update all the states of the entity objects which will affect the results of a SELECT query.</p>
<p>The AUTO flush mode can be set explicitly on the Query by calling setFlushMode().</p>
<pre class="brush: java; title: ; notranslate">queryObject.setFlushMode(FlushModeType.AUTO);</pre>
<p>When the flush mode is set to COMMIT, then the persistence engine, may only update all the state of the entities during the database COMMIT. The dirty changes applied to entity objects and then querying for the results of the entities may be unspecified.</p>
<pre class="brush: java; title: ; notranslate">queryObject.setFlushMode(FlushModeType.COMMIT);</pre>
<p>[The method setFlushMode(FlushModeType) is available in both EntityManager and Query interface. If the EntityManager has been configured with setFlushMode(FlushModeType.AUTO) and the Query object has been called with setFlushMode(FlushModeType.COMMIT), then the preference will always goes to the Query object.]</p>
<h2>Persistent Units</h2>
<p>Before getting into the theory of what is a persistence unit and how it has relations with EntityManagerFactory and EntityManager, let us look into a sample persistence.xml file.</p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;persistence&gt;
	&lt;persistence-unit name=&quot;EmployeePersistentUnit&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt; &lt;provider&gt;oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider&lt;/provide&gt;
		&lt;class&gt;com.javabeat.ejb30.persistence.entities.Employee&lt;/class&gt;
		&lt;properties&gt;
		  vproperty
	name=&quot;toplink.jdbc.url&quot; value=&quot;jdbc:derby://localhost:1527/sample&quot;/&gt;
		  &lt;property
	name=&quot;toplink.jdbc.user&quot; value=&quot;app&quot;/&gt;
	 &lt;property
	name=&quot;toplink.jdbc.driver&quot; value=&quot;org.apache.derby.jdbc.ClientDriver&quot;/&gt;
		  &lt;property name=&quot;toplink.jdbc.password&quot; value=&quot;app&quot;/&gt;
		  &lt;property name=&quot;toplink.ddl-generation&quot; value=&quot;drop-and-create-tables&quot;/&gt;
		&lt;/properties&gt;
	  &lt;/persistence-unit&gt;
	&lt;/persistence&gt;
</pre>
<p>[A persistence.xml file is used to manage one or more persistence units. Like web.xml for a servlet application and ejb-jar.xml for an EJB application, this persistence.xml is a must for an entity application to run.]</p>
<p>At a very high-level, we can infer multiple persistence units within the same persistence.xml file being uniquely identified by its name tag. Each persistence unit is configured with a provider along with its data-source and with some set of entities. So, we can say that a persistence unit provides a logical grouping for some set of entities that share some configuration.</p>
<p>Imagine an application is having so many entity objects and these entity objects have been nicely categorized in a way that some set of entities are sharing a common provider (Toplink, for example), acting on some data-source, whereas other set of entities are depending on a different provider (Hibernate, for example). In such a case, we can define a persistent unit with some configuration properties for some set of entities and a different persistent unit with different set of configuration properties for the remaining entities. So a persistent unit is a way to categorize some set of entities that aimed to do some common goals and common configurations to share with.</p>
<p>Back to the above sample code, we have two different persistent units, one being configured to point to Toplink provider with the help oftag, and the other one pointing to a hibernate provider. We also have put some vendor specific hints (or properties) through the property tag (found within the properties tag). The meaning of toplink.ddl-generation with value drop-and-create-tables essentially tells the Toplink persistence engine that during deployment time, if already there exists a table for the corresponding class MobileEntity, just drop (delete ) the table and create it before using. Similarly the property-value pair “hibernate.hbm2ddl.auto-update” tells the persistence engine, to use the existing table and not to recreate it. Thetag represents the name of entity class that is to be included as part of this persistent unit.</p>
<p>Now, that we have a basic understanding about persistent units that how they are useful in categorizing entity objects, now its time to see how EntityManager and persistent units are related. In a regular J2SE application, instances of EntityManager class are obtained through EntityManagerFactory which is turn is obtained through the boot-strap class Persistence.</p>
<p>The following shows the sample code to achieve the same,</p>
<pre class="brush: java; title: ; notranslate">String persistentUnitName = &quot;MyMobilePersistentUnit&quot;;
	EntityManagerFactoryfactory  factory = Persistence
                 .createEntityManagerFactory(persistentUnitName);
                       // Line 1

	EntityManager entityManager = factory.createEntityManager();
                    // Line 2</pre>
<p>In line 1, an instance of EntityManagerFactory is obtained with a call to createEntityManagerFactory() with the name of the persistent unit being passed as an argument. At this stage, we know that the persistent unit by name MyMobilePersistentUnit has been configured with Toplink as its provider along with a data source object with some additional vendor specific properties. Therefore, EntityManager objects being created for this kind of configuration from the EntityManagerFactory have this configuration for their entire life-time.</p>
<p>In the case of a J2EE application , one can instantiate an instance of EntityManager object backed up with @PersistentUnit like this,</p>
<pre class="brush: java; title: ; notranslate">@PersistentUnit(unitName = &quot;MyMobilePersistentUnit&quot;)
	private EntityManager entityManager;</pre>
<p>Now, the EntityManager object will have the set of configuration parameters being loaded as referenced by the persistent unit name "MyMobilePersistentUnit".</p>
<blockquote><p><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2007/04/jpa/">Introduction to JPA</a></li>
<li><a href="http://www.javabeat.net/2007/04/sample-application-for-java-persistence-api-jpa/">Sample Application Using JPA</a></li>
</ul>
</blockquote>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/04/the-query-api-in-jpa-ejb-3-0/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Introduction to Java Persistence API(JPA)</title>
		<link>http://www.javabeat.net/2007/04/jpa/</link>
		<comments>http://www.javabeat.net/2007/04/jpa/#comments</comments>
		<pubDate>Fri, 13 Apr 2007 07:50:11 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JPA]]></category>
		<category><![CDATA[Java Persistence API (JPA)]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=12</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p><strong>Java Persistence API (JPA)</strong> provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with <strong>Java Persistence API</strong> starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of <strong>JPA</strong> is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications.<em> [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes.</em></p>
<blockquote><p><span style="text-decoration: underline;"><strong>also read<em></em></strong></span>:</p>
<ul>
<li><a href="http://www.javabeat.net/2007/04/the-query-api-in-jpa-ejb-3-0/">The Query API in JPA (EJB 3.0)</a></li>
<li><a href="http://www.javabeat.net/2007/04/sample-application-for-java-persistence-api-jpa/">Sample Application for Java Persistence API (JPA)</a></li>
</ul>
</blockquote>
<pre class="brush: java; title: ; notranslate">class MyServlet extends HttpServlet {}
	class MyRemote implements SessionBean {}</pre>
<p>In the above cases, both MyServlet and MyRemote extends and implement specialized Servlet and Bean classes, therefore, these classes cannot be termed as POJO’s.</p>
<p>When we say that JPA follows the POJO standard, it follows that the entities (or the entity class) are very regular and normal Java classes, in the sense that they doesn’t need to extend or implement some specialized classes].</p>
<p><em><br />
[OR Mapping – Object-Relation mapping is the process of the transformation of the data between the class objects and databases. Applications can depend on an OR-M like tool that greatly simplifies this work instead of manually coding the transformation process.]</em></p>
<h2>About Persistence Entites</h2>
<p>Persistent Data normally refers to permanent data in an application. The state of these data is made permanent by storing them in a persistent medium like database, files or a disk tape. In <strong>JPA</strong> terms, these persistent data are referred as entities. An entity refers to a logical collection of data that can be stored or retrieved as a whole. For example, in a banking application, Customer and BankAccount can be treated as entities. Customer name, customer address etc can be logically grouped together for representing a Customer entity. Similarly account number, total balance etc may be logically grouped under BankAccount entity.</p>
<p>Since entities form the heart of the JPA, they have some unique characteristics like persistability, identity and transactionability. The property of persistability deals with the storing and retrieving of entity from and to a persistent medium like database. Identity property is usually used to identity one unique entity among multiple entities (or multiple entity instances) in a database. All the CRUD operations (Create, Update and Delete) for entity objects will occur within a transactional context and it is one of the major characteristic for an entity object as the real state of an entity depends whether a transaction completes (commits/fails) or not.</p>
<h2>Persistence API</h2>
<p>All the classes, interfaces and annotations that make up the <strong>Java Persistence API</strong> are available in a single javax.persistence package. A brief look at the core objects and concepts within the package will be much useful before dealing with some sample code.</p>
<h2>Entites</h2>
<p>As mentioned previously, in <strong>JPA</strong> terms an entity refers to a persistent object which can be stored and retrieved from a persistent storage. In technical terms, this entity will correspond to a Java class.</p>
<p>Consider the following simple java class, named MobileEntity.</p>
<pre class="brush: java; title: ; notranslate">class MobileEntity{

	private String model;
	private String manufacturer;
	private Double price;
      private String imeiNo;

	…..
	// Getters and Setters go here.
}</pre>
<p>The above class represents a mobile object which has its own model, manufacturer, price and an imei number. Suppose, we wish to persist this mobile java class using <strong>JPA</strong>. The first step is to qualify this java class as an entity. This is done by marking the class with @Entity annotation. Marking a class with @Entity annotation will tell to the persistence engine that objects created from this class can use the support of <strong>JPA</strong> to make them persistent. After adding the @Entity annotation to the above class the code looks like this,</p>
<pre class="brush: java; title: ; notranslate">@Entity
class MobileEntity{

	private String model;
	private String manufacturer;
private Double price;
	private String imeiNo;

	…..
	// Getters and Setters go here.
}</pre>
<p>[A persistence engine or a persistence provider is nothing but an implementation of the <strong>Java Persistence API</strong>. <strong>Java Persistence API</strong> is just a specification from Sun and not an implementation and vendors are free to implement their own persistent framework following the JPA specification. Thus, <strong>JPA</strong> provided a pluggable interface, where more and more implementations can easily be associated with it at run-time.]</p>
<p>Since an entity always has an identity associated with it, it is the job of the programmer to tell to the persistence engine, how uniquely to identity an entity object. This is simply done by marking a field (or a set of fields) with the @Id annotation. A field that is marked with @Id annotation will be treated as a primary key for the table by the persistent engine.</p>
<p>It is an error to ignore any one of the fields in an Entity class with @Id annotation, because the persistence engine won’t be in a position to identity unique entity objects without the help of primary keys. In our case, since no two mobile phones in the world share the same IMEI (International Mobile Equipment Identity), imeiNo is an ideal candidate to be marked with @Id annotation.</p>
<pre class="brush: java; title: ; notranslate">@Id
	private String imeiNo;</pre>
<p>It is an error to give null values, to a primary key field, during that case, the persistence engine may throw any kind of database exception.</p>
<p>The following is the default values for table and column names when the persistence engine was Oracle’s Toplink during the deployment time.</p>
<ul>
<li>Alias Name &#8211; MobileEntity (the unqualified (with-out the package name) name of the class).</li>
<li>Table Name &#8211; MOBILEENTITY</li>
<li>Column Names &#8211; [MODEL, MAUNFACTURER, PRICE and IMEINO] (These correspond to the variable names).</li>
</ul>
<h2>Customizing the Entity object</h2>
<p>In most of the cases, the defaults that are created and provided by a persistence engine are sufficient. However, certain situations may demand for customization which includes factors like name collision, companies adopting standard naming conventions, etc., like that. In such a case, the entity class can greatly be customized with a huge set of annotations available in the javax.persistence package. Let us take a look one by one.</p>
<h2>Changing the default table name</h2>
<p>By default the table name corresponds to the unqualified name of the class. We can change this behavior with the help of @Entity annotation itself, like this.</p>
<pre class="brush: java; title: ; notranslate">@Entity(name = &quot;MOBILE_ENTITY&quot;)
	public class MobileEntity{
	……
	}</pre>
<p>Now, the table name becomes MOBILE_ENTITY and this should be the name that must be referred in query strings (Queries are discussed later). The value to the name property must be legal in the sense, it cannot accept any keywords that are found in the query language.</p>
<h2>Customizing the Column behaviors</h2>
<p>The default name of the columns, their size, whether they can accept null values or not etc., can be customized using the @Column annotation. Following is the sample code that illustrates this,</p>
<pre class="brush: java; title: ; notranslate">@Column(name = &quot;MOBILE_MODEL&quot;, nullable = true, length = 35)
	private String model;

	@Column(name = &quot;MOBILE_MANUFACTURER&quot; nullable = true, length = 100)
	private String manufacturer;

	@Id
	@Column(name = &quot;MOBILE_IMEI_NO&quot;, nullable = false)
	private String imeiNo;</pre>
<p>The name property, when specified will override the default column name (which is the same as that of the field name in the Entity class). The nullable property tells that whether the column can accept null values. Length property is only applicable if the type of the column is String (or VARCHAR). There are also properties like scale and precision which is applicable only when the type of the column is NUMBER.</p>
<p><em><br />
[Note, multiple annotations can be legally applied to elements (like class, field, method etc.). In the above example the imeiNo has two annotations attached with it, namely @Id and @Column.]<br />
</em></p>
<h2>Auto-generation of Primary Keys</h2>
<p>A primary key for an entity which is usually annotated with @Id annotation can be given a value manually or we can depend on the persistence provider for the same. For this we have to use the @GeneratedValue annotation.</p>
<p>Consider the following example,</p>
<pre class="brush: java; title: ; notranslate">@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private String imeiNo;</pre>
<p>Since the imeiNo is going to be the primary key for the mobile object, we have decorated the field with @GeneratedValue annotation, which delegates the burden of creating values from developers to the persistence engine. Also, there are 4 different methods (or strategies) for primary key generation, which are AUTO, IDENTITY, SEQUENCE and TABLE. The simplest one is the automatic primary key generation strategy which is represented as GenerationType.AUTO.</p>
<p><em><br />
[GenerationType is an Enumeration (new feature in Java 5.0) and the four different strategies for primary key generation, namely AUTO, IDENTITY, TABLE and SEQUENCE are defined in that enumeration.]</em></p>
<h2>EntityManager</h2>
<p>This class follows the standard Manager Design pattern for managing entities. Managing an entity or a set of entities refers to the act of bring a set of Java objects under the control of EntityManager. Unless entities don’t have any explicit association with EntityManager they are just ordinary java objects (though their corresponding classes have been marked with @Entity annotation).</p>
<p>This EntityManager API provides services for persisting an entity, removing an entity, querying and deleting entities.</p>
<p>In a J2SE application, a reference to an entity manager (EntityManager) can be obtained using the entity manager factory (EntityManagerFactory) and the Persistence class. The persistence class is a helper class (or a bootstrap) used to create EntityManagerFactory objects. With EntityManagerFactory objects, references to EntityManager objects can be obtained. The following code illustrates the same,</p>
<pre class="brush: java; title: ; notranslate">EntityManagerFactory entityManagerFactory =
  Persistence.createEntityManagerFactory(&quot;PersistentUnitName&quot;);
  EntityManager eManager = entityManagerFactory.createEntityManager();
</pre>
<p><em><br />
[An EntityManagerFactory can be configured with some set of properties with the help of Persistent Units. Notice that one of the arguments to createEntityManagerFactory() is the name of the persistent unit which is discussed in the later sections.]<br />
</em></p>
<p>In a J2EE application, the container will directly inject a reference to the EntityManager using dependency injection, so the code becomes as simple like this,</p>
<pre class="brush: java; title: ; notranslate">
@Resource
private EntityManager entityManager;</pre>
<h2>Persistence Context</h2>
<p>To be very precise, a persistent context manages a set of entities which in turn is managed by the EntityManager. A persistent context keeps track of the state (or the changes) that an entity object may undergo. And the EntityManager takes the support of this persistence context to commit or to undo the changes. As soon as an EntityManager object is created, it is implicitly associated with a persistence context for managing a set of entities.</p>
<p>Persistent Context comes in two flavors, one is the transaction-scoped persistent context and the other one is extended persistent context.</p>
<p><strong>Transaction-Scoped Persistence Context:</strong> Imagine that a set of entities are managed by the persistence context. At this time, we say that the entities are bound to (or attached) to the persistent context. Changes may happen to these entities and these changes will occur within a transaction. Sometimes later when the transaction ends (commits or roll-back), the entities will unbind (detached) from the persistent context. As soon as the entities are detached from the persistence context, they are no longer being managed. Any changes that happen to these entities will not be persisted as they don’t have any association with the persistence context. Such kind of persistent context whose life-time is dependent on the life-time of the transaction (for a set of entities at that particular point of time) is termed as transaction-scoped persistent context.</p>
<p>All the transaction-scoped persistence context are configured by injecting @PersistentContext to EntityManager objects , like this,</p>
<pre class="brush: java; title: ; notranslate">
@PersistenceContext(name=&quot;PersistentUnitName&quot;)
private EntityManager entityManager;
</pre>
<p><em> [Note: There is no such public interface called PersitenceContext in the Java Persistence API. The EntityManager may implicitly depend on a virtual Persistence Context class for managing the entities. So, creating a transaction-scoped persistence context is nothing but creating an EntityManager object that has been configured with @PersistenceContext annotation.]<br />
</em></p>
<p><strong>Extended Persistence Context:</strong> Unlike transaction-scoped persistence context, where the life-time of the persistence context will end as soon the transaction is completed, a persistence context may be configured to live even after a transaction completes. In such a case, all the entities that are managed by such a persistence context will still be in a manageable state only even after the transaction ends. They won’t be detached from the context. Such long-lived persistence context that will continue to exist even after the completion of a transaction is called extended persistence context.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>All the extended persistence context objects are created and managed manually by the application code only (that is by the developers).</p>
<p>[As soon as an EntityManager object is created, an implicit Persistence context will be associated with it and it is soon kept open and prepared for managing a set of entities, meaning that the calling EntityManager.isOpen() method will always return true. Calling the EntityManager.clear() method will clear the current persistence context associated with the EntityManager and all the entities that have their associations will now be cleared and they become detached from the EntityManager. To release all the resources referenced by the EntityManager, call the close() method, After this method call, calling any of the methods will throw IllegalStateException.]</p>
<h2>Entities and Transactions</h2>
<p>All entities have the property of transactionability and their CRUD operations will take place within a transactional context. Transactions can be broadly classified into two types based on who actually owns (or manages) the transaction. They are JTA and Resource-local transaction.</p>
<p>In the case of a J2EE Application, the default transaction type is JTA (Java Transaction API), unless explicitly specified. A method can be simply annotated with @RequiresNew (or @Requires) in which case a new transaction will always started by the container and the transaction completes as soon as the method ends.</p>
<p>Whereas in a J2SE application, the transaction-type defaults to Resource-local, which means that the developer (or the application code) has to explicitly start and end a transaction. It means that the user has to explicitly start a transaction with the help of EntityManager object, and then have to commit it, if everything goes normal, else have to roll-back the transaction if some error occurs.</p>
<p>The following code shows this,</p>
<pre class="brush: java; title: ; notranslate">
EntityTransaction userTransaction = entityManager.getTransaction();
  try{
	userTransaction.begin();

	 // Do something here.

	// If everthing goes well, make a commit here.
	userTransaction.commit();
	}catch(Exception exception){
		// Exception has occurred, roll-back the transaction.
		userTransaction.rollback();
	}
</pre>
<h2>Operations on Entity Objects</h2>
<p>The following are the legal operations that can be performed on Entity objects with the help of EntityManager API. As seen previously, EntityManager are objects that manage one or more entity objects with the help of an implicit persistence context.</p>
<p><strong>Persisting Entity Objects:</strong></p>
<p>Entity objects are like regular java objects until they become managed and made persistent by the EntityManager. The following piece of code makes an entity to become persistent and managed.</p>
<pre class="brush: java; title: ; notranslate">MobileEntity mobileObject = new MobileEntity();
	mobileObject.set()... // Update the state values here.
	entityManager.persist(mobileObject);</pre>
<p>The persist(entityObject) methods makes the entity persistent in the underlying database and managed within the persistence context of the EntityManager, whether the persistence context is a transaction-scoped or an extended persistence context depends upon how actually the EntityManager was configured.</p>
<p>[What happens when a managed entity is again forced to become managed by calling the persist() method. Or what happens when the persist() method is called couple of times on the same entity object.</p>
<p>Whenever the persist() method is called, the persistence engine will check for the existence of that object with the help of its unique identifier (which is represented in the form of primary key). If any duplicate object is found, then a run-time exception, EntityExistsException will be thrown.]</p>
<p><strong><br />
Querying for Entities:</strong></p>
<p>Developers can either depend on the EntityManager for simple search or Query objects for providing powerful search conditions for locating and querying entity objects.</p>
<p><strong><br />
Using EntityManager object:</strong></p>
<p>Following are the two different methods available in EntityManager interface for querying entity objects and there are some major differences between the two.</p>
<p><strong>Using the EntityManager.find() method: </strong></p>
<p>The find() method takes the class name of the Entity object and the primary key value for locating a single entity object. If the object of interest cannot be located by the EntityManager, then this method will simply return null. The following code illustrates this,</p>
<pre class="brush: java; title: ; notranslate">
MobileEntity mobile = entityManager.find(MobileEntity.class, &quot;ABC-123&quot;);
 If (mobile != null){ // mobile object may or may not be null.
 // Process the object.
 }
</pre>
<p>One good thing about the find() method is that, the returned entity object soon becomes managed automatically within the persistence context of the EntityManager.</p>
<p><strong><br />
Using the EntityManager.getReference() method:</strong></p>
<p>This method, like the EntityManager.find() method, takes the name of the entity class and the primary key as their arguments. But the difference is, unlike the find() method which will return null if the entity object is not found, this method will throw an exception EntityNotFFoundException. Another difference between this method and the find() method is that, the entity that is fetched by this method may be lazily loaded. That is, the state of the state of entity (like model, manufacturer, imeiNo may be lazily loaded during the first time it is actually accessed).</p>
<pre class="brush: java; title: ; notranslate">
MobileEntity mobile = entityManager.getReference(
     MobileEntity.class, &quot;ABC-123&quot;);
// mobile object may not contain the actual state
//values for model, manufacturer
// and imei number, the states may be loaded during the first access.

String model = mobile.getModel();
// The persistence engine may fetch the model value for the mobile here
// at this particular point of time.
…..</pre>
<p><strong><br />
Using the Query object:</strong><br />
Discussed later.</p>
<p><strong><br />
Deleting Entities:</strong></p>
<p>To remove (delete) an entity object from the database, make a call to EntityManager.remove(entityObject) method. The entity object that is passed to the remove() must be a managed entity, else the operation will fail.</p>
<p>Also, making this call may or may-not remove the entity immediately from the database. The algorithm that achieves the same is implementation specific. Some implementation may only mark the entity as a removed entity after this method call, and the actual deletion of the entity object in the database may happen when a flush() operation (which is discussed later) is made.</p>
<p>After this method call, the entity will become detached from the persistence context and it is no longer a managed one.</p>
<p><strong><br />
Updating Entities:</strong></p>
<p>The EntityManager.merge(entityObject) method will make a detached entity to get associated with the current persistence context of the EntityManager. Consider the following lines of code.</p>
<pre class="brush: java; title: ; notranslate">
// Transaction has begin.
…..
MobileEntity mobile = entityManager.find(MobileEntity.class, &quot;ABC-123&quot;);
…..
// Transaction ends.
mobile.set()…… // Updating the mobile object.
entityManager.merge(mobile);
</pre>
<p>In the above piece of code, a mobile entity object is located with the EntityManager.find() method. This entity is now in a managed state. Assume that the transaction ends after some point of time and also the persistence context is a transaction-scoped persistence context. As soon as the transaction completes, the persistence context will go off, (since the persistence context is a transaction-scoped persistence context). So the entity object becomes detached from the persistence context. After this any modifications that are made to the mobile object won’t be knowledgeable to the EntityManager as the mobile object has already been detached from it.</p>
<p>Now, calling the merge() method, will make the mobile object becomes managed, and all the recent changes that are made to it will become visible to the current persistence context of the EntityManager.</p>
<p><strong><br />
Flushing and Refreshing:</strong></p>
<p>The EntityManager.flush() will synchronize all the changes that are made to the persistent entities back to the underlying database, whereas the EntityManager.refresh() does the reverse. It will update the entity object with values taken from the database. Any new values that are set to the entity objects will be lost as a result of this method call.</p>
<p>For example, consider the following piece of code,</p>
<pre class="brush: java; title: ; notranslate">MobileEntity mobile = …..
	mobile.set(); // Update the state values for the mobile object.
	….
	entityManager.flush();
	// Calling this flush method will synchronize the database with the values
	// taken from the entity object.</pre>
<p>Now consider this code,</p>
<pre class="brush: java; title: ; notranslate">MobileEntity mobile = …
	mobile.set(); // The state values for the mobile object is updated.
	…..
	entityManager.refresh();
	// The refresh() method will refresh the entity object
        //with the values taken from the database.
	// All the updates that are done are lost.</pre>
<h2>Summary</h2>
<blockquote><p><span style="text-decoration: underline;"><strong>also read<em></em></strong>:</span></p>
<ul>
<li><a href="http://www.javabeat.net/2007/04/the-query-api-in-jpa-ejb-3-0/">The Query API in JPA (EJB 3.0)</a></li>
<li><a href="http://www.javabeat.net/2007/04/sample-application-for-java-persistence-api-jpa/">Sample Application for Java Persistence API (JPA)</a></li>
</ul>
</blockquote>
<p>The above two links are continuous of this article with more features and the sample application for the <strong>JPA</strong>.This article began with the discussion of <strong>Java Persistent API</strong> and its advantages and what persistent entities are. Then the terminologies that are very specific to <strong>JPA like EntityManager</strong>, <strong>PersistenceContext</strong> have been discussed. The various features about the Query interface for locating Entity objects were explored in depth. Finally, it ended with Persistent Units and its relation with <strong>EntityManager</strong> objects along with a sample J2SE application.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/04/jpa/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
