<?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; EJB 3.0</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/ejb-3-0/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Tue, 21 May 2013 13:43:42 +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>How to create EJB project in NetBeans 7.0?</title>
		<link>http://www.javabeat.net/2011/06/how-to-create-ejb-project-in-netbeans-7-0/</link>
		<comments>http://www.javabeat.net/2011/06/how-to-create-ejb-project-in-netbeans-7-0/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 23:30:32 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>
		<category><![CDATA[NetBeans]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2399</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>NetBeans IDE 7 CookbookWelcome to the NetBeans Cookbook. NetBeans is a Java Integrated Development Environment, IDE, which enables fast application development with the most adopted frameworks, technologies, and servers. Different than other IDEs, NetBeans comes already pre-packaged with a wide range of functionality out of the box, such as support for different frameworks, servers, databases, [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p><center>NetBeans IDE 7 Cookbook</center>Welcome to the NetBeans Cookbook.</p>
<p>NetBeans is a Java Integrated Development Environment, IDE, which enables fast<br />
application development with the most adopted frameworks, technologies, and servers.</p>
<p>Different than other IDEs, <strong>NetBeans</strong> comes already pre-packaged with a wide range of<br />
functionality out of the box, such as support for different frameworks, servers, databases,<br />
and mobile development.</p>
<p>This book does require a minimal knowledge of Java platform, more specifically the<br />
language ifself. But the book might as well be used by either beginners, who are trying to<br />
dip their toes in new technology, or more experienced developers, who are trying to<br />
switch from other IDEs but want to decrease their learning curve of a new environment.<br />
<strong>NetBeans</strong> integrates so many different technologies, many of which are present in this<br />
book, that it is beyond the scope of this book to cover all of them in depth. We provide<br />
the reader with links and information where to go when further knowledge is required.</p>
<h1>What This Book Covers</h1>
<p><em>Chapter 1, NetBeans Head First</em> introduces the developer to the basics of <strong>NetBeans</strong> by<br />
creating basic Java projects and importing Eclipse or Maven projects.</p>
<p><em>Chapter 2, Basic IDE Usage</em> covers the creation of packages, classes, and constructors, as<br />
well as some usability feature.</p>
<p><em>Chapter 3, Designing Desktop GUI Applications</em> goes through the process of creating<br />
a desktop application, then connecting it to a database and even modifying it to look<br />
more professional.</p>
<p><em>Chapter 4, JDBC and NetBeans</em> helps the developer to setup <strong>NetBeans</strong> with the most<br />
common database systems on the market and shows some of the functionality built-in to<br />
<strong>NetBeans</strong> for handling SQL.</p>
<p><em>Chapter 5, Building Web Applications</em> introduces the usage of web frameworks such as<br />
JSF, Struts, and GWT.3</p>
<p><em>Chapter 6, Using JavaFX</em> explains the basic of JavaFX application states and connecting<br />
our JavaFX app to a web service interface.</p>
<p><em>Chapter 7, EJB Application</em> goes through the process of building an <strong>EJB</strong> application<br />
which supports <strong>JPA</strong>, stateless, and stateful beans and sharing a service through a web<br />
service interface.</p>
<p><em>Chapter 8, Mobile Development</em> teaches how to create your own CLDC or CDC<br />
applications with the help of <strong>NetBeans</strong> Visual Mobile Designer.</p>
<p><em>Chapter 9, Java Refactoring lets</em> <strong>NetBeans</strong> refactor your code to extract classes,<br />
interfaces, encapsulate fields, and other options.</p>
<p><em>Chapter 10, Extending the IDE</em> includes handy examples on how to create your own<br />
panels and wizards so you can extend the functionality of the IDE.</p>
<p><em>Chapter 11, Profiling and Testing</em> covers <strong>NetBeans</strong> Profiler, HTTP Monitor, and<br />
integration with tools that analyze code quality and load generator.</p>
<p><em>Chapter 12, Version Control</em> shows how to configure <strong>NetBeans</strong> to be used with the most<br />
common version control systems on the market.</p>
<p><center>EJB Application</center>In this chapter, we will cover:</p>
<ul>
<li>Creating an EJB project</li>
<li>Adding JPA support</li>
<li>Creating Stateless Session Bean</li>
<li>Creating Stateful Session Bean</li>
<li>Sharing a service through Web Service</li>
<li>Creating a Web Service client</li>
</ul>
<h2>Introduction</h2>
<p><strong>Enterprise Java Beans (EJB)</strong> is a framework of server-side components that encapsulates<br />
business logic.</p>
<p>These components adhere to strict specifications on how they should behave. This ensures<br />
that vendors who wish to implement <strong>EJB</strong>-compliant code must follow conventions, protocols,<br />
and classes ensuring portability.</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>The <strong>EJB</strong> components are then deployed in <strong>EJB</strong> containers, also called <strong>application servers</strong>,<br />
which manage persistence, transactions, and security on behalf of the developer.</p>
<p>If you wish to learn more about <strong>EJB</strong>s, visit http://jcp.org/en/jsr/detail?id=318 or</p>
<p>https://www.packtpub.com/developer-guide-for-ejb3/book.</p>
<p>For our <strong>EJB</strong> application to run, we will need the application servers.</p>
<p>Application servers are responsible for implementing the <strong>EJB</strong> specifications and creating the<br />
perfect environment for our <strong>EJB</strong>s to run in.</p>
<p>Some of the capabilities supported by <strong>EJB</strong> and enforced by Application Servers are:</p>
<ul>
<li>Remote access</li>
<li>Transactions</li>
<li>Security Scalability</li>
</ul>
<p><strong>NetBeans 6.9</strong>, or higher, supports the new Java EE 6 platform, making it the only IDE so far<br />
to bring the full power of <strong>EJB 3.1</strong> to a simple IDE interface for easy development.</p>
<p><strong>NetBeans</strong> makes it easy to develop an <strong>EJB</strong> application and deploy on different Application<br />
Servers without the need to over-configure and mess with different configuration files. It&#8217;s<br />
as easy as a project node right-click.</p>
<h2>Creating EJB project</h2>
<p>In this recipe, we will see how to create an <strong>EJB</strong> project using the wizards provided<br />
by <strong>NetBeans</strong>.</p>
<h3>Getting ready</h3>
<p>It is required to have <strong>NetBeans</strong> with Java EE support installed to continue with this recipe.</p>
<p>If this particular <strong>NetBeans</strong> version is not available in your machine, then you can download it<br />
from http://download.netbeans.org.</p>
<p>There are two application servers in this installation package, Apache Tomcat or GlassFish,<br />
and either one can be chosen , but at least one is necessary.</p>
<p>In this recipe, we will use the GlassFish version that comes together with NetBeans 7.0<br />
installation package.</p>
<h3>How to do it&#8230;</h3>
<ol>
<li>Lets create a new project by either clicking <strong>File</strong> and then <strong>New Project</strong>, or by pressing<br />
<em>Ctrl+Shift+N</em>.</li>
<li>In the <strong>New Project</strong> window, in the categories side, choose <strong>Java Web</strong> and in <strong>Projects<br />
side</strong>, select <strong>WebApplication</strong>, then click <strong>Next</strong>.</li>
<li>In <strong>Name and Location</strong>, under Project Name, enter <strong>EJBApplication</strong>.</li>
<li>Tick the <strong>Use Dedicated Folder for Storing Libraries</strong> option box.</li>
<li>Now either type the folder path or select one by clicking on <strong>browse</strong>.</li>
<li>After choosing the folder, we can proceed by clicking <strong>Next</strong>.</li>
<li>In <strong>Server and Settings</strong>, under <strong>Server</strong>, choose <strong>GlassFish Server 3.1</strong>.</li>
<li>Tick <strong>Enable Contexts and Dependency Injection</strong>.</li>
<li>Leave the other values with their default values and click <strong>Finish</strong>.</li>
</ol>
<p>The new project structure is created.</p>
<h3>How it works&#8230;</h3>
<p><strong>NetBeans</strong> creates a complete file structure for our project.</p>
<p>It automatically configures the compiler and test libraries and creates the GlassFish<br />
deployment descriptor.</p>
<p>The deployment descriptor filename specific for the GlassFish web server is<br />
glassfish-web.xml.</p>
<p><center><img src="images/2011/06/ejb-application/ejb-application-1.jpg" alt="" /></center></p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-j2ee%2Fejb-3-0%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/ejb-3-0/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/ejb-3-0/feed/" data-count="vertical" data-text="EJB 3.0" 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/06/how-to-create-ejb-project-in-netbeans-7-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Stateless Session Beans in EJB 3.0</title>
		<link>http://www.javabeat.net/2011/04/stateless-session-beans-in-ejb-3-0/</link>
		<comments>http://www.javabeat.net/2011/04/stateless-session-beans-in-ejb-3-0/#comments</comments>
		<pubDate>Wed, 06 Apr 2011 15:14:24 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=629</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 based on EJB3 in Action, Second Editionand the book will release on October 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile [...]</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><em>This article is based on <a href="http://www.manning.com/panda2/">EJB3 in Action, Second Edition</a>and the book will release on October 2011. It is being reproduced here by permission from <a href="http://www.manning.com">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.</em></p>
<h1 style="text-align: center;">Stateless Session Beans</h1>
<h2>Introduction</h2>
<p>Stateless session beans are probably the most common bean type used in an application. A stateless session bean doesn’t maintain a conversational state. This means that session beans tasks must be completed in a single method call. This does not limit a stateless session bean to containing only one method. To the contrary, a stateless session beans usually contain at least several closely related business methods. Of the session bean types, stateless session beans have the best performance characteristics. To understand why, take a close look at figure 1 that shows a high-level schematic of how stateless session clients typically use beans.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/15.jpg"><img class="aligncenter size-medium wp-image-1168" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/04/15-300x235.jpg" alt="" width="300" height="235" /></a><strong>Figure 1 Complex stateless session bean application using nested transactions.</strong></p>
<p>Stateless session beans are pooled. This means that, for each managed bean, the container keeps a certain number of bean instances ready in a pool. For each client request, an instance from the pool is quickly assigned to service the request. When the client finishes, the instance is returned to the pool for later reuse. This setup using a pool means that a small number of bean instances can service a relatively large number of clients. Don’t forget that these one-shot methods come with a number of services provided by the container.</p>
<p>In this article, you’ll learn about developing stateless session beans. We’ll start off by first looking at when stateless session beans are appropriate.</p>
<h2>When to use stateless session beans</h2>
<p>Session beans should be used to encapsulate business logic when you need dependency injection, transaction management, concurrency, security, remoting, scheduling, and support for interceptors. You specifically use a stateless session bean when the business logic you are implementing requires these services and can be performed within a single method call and the response is tailored for the client. This is an atomic piece of work that maintains no state after the method completes. The client may maintain state but the stateless session bean does not. To expound upon these basic guidelines we need to look to the prototypical session bean and then step back and look at the bigger picture.</p>
<p>To understand when to use stateless session beans let’s consider the prototypical use case that best exemplifies a stateless session bean. A stateless session bean should be a class with several methods that perform related operations such as managing users, updating account information, or managing bids. The related operations are all one shot; the bean doesn’t maintain any state after the method invocation is completed from the perspective of the client. The methods consume services such as database connections and possibly require security to enforce access control. The business operations performed by the bean are not static. They aren’t serving up the same data regardless of the client.</p>
<p>Stateless session beans may use other stateless session beans. These stateless session beans may interact with other database tables, resources, and have additional security requirements. Beans may and often will, use other beans. Figure 1 shows a design with multiple stateless session beans interacting with each other. Each of these beans uses transactions and also has security authorization requirements. A failure in the SAP Integration Bean should result in a rollback in the transaction in the Inventory and Bid Manager Beans. In this example, stateless session beans are joining transactions started by the parent stateless session bean and this is possibly being propagated down several levels. Thus, when trying to decide whether to make an object a stateless session bean, we have to approach it from the perspective of the services the methods require and how they are consumed by their clients.</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>We’ve just identified when to use stateless session beans but consideration should also be given to when not to use them. If you aren’t using any container services, such as remoting, injection, database resources, and so on, making a class a stateless session bean isn’t beneficial and overall application performance can suffer. If functionality in question is simply saving form data to a database, a JSF backing bean with an injected persistence context is more appropriate. In other words, now that you are familiar with stateless session beans, don’t turn every non-JPA POJO into a stateless session bean.</p>
<h2>Stateless session bean pooling</h2>
<p>As we see in figure 2 session beans are pooled by the container.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/23.jpg"><img class="aligncenter size-medium wp-image-1167" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/04/23-300x208.jpg" alt="" width="300" height="208" /></a><strong>Figure 2 A singleton bean is instantiated once by the container. Each client accesses the same instance of a singleton session bean.</strong></p>
<p>Whenever a request arrives for a bean, the container allocates a bean. When the stateless session bean’s method returns, the bean is placed back into the pool. Thus a bean is either servicing a request or waiting for a request in the pool. The pool serves two important functions. First, it ensures that there are objects ready to service a request when one arrives. Second, the pool bounds the number of instances that can be created. By keeping instances around to service requests, we minimize the amount of time it takes to begin servicing a request. If, every time a request arrived at the server, an object had to be instantiated and database connections established, a significant amount of time would be wasted. It would be analogous to going to a restaurant and waiting for the restaurant to run out and hire another waiter. At the opposite end of the spectrum, too many requests could flood the server and overwhelm available resources. If the container created another stateless session bean each time one was needed, the application could eventually exhaust resources. There is a limit to the number of database connections that can be open as well as the number of clients that can be serviced concurrently. Create too many objects fast and then toss them away, garbage collection will kick in and slow the application. Hence, limiting the size of the pool is a necessity.</p>
<p>The benefits of pooling stateless session beans should be obvious. You want to minimize the number of objects created to keep garbage collection from impacting the application while at the same time keeping some instances around to service requests. The act of balancing these two comes down to performance tuning. Each application container does performance tuning a little bit differently. As you develop and test your application, the tuning of this pool will be necessary. For instance, consider some of the pool settings available in the Glassfish server:</p>
<ul>
<li>Initial and minimum pool size—The minimum number of beans to appear in the pool. The default is 0.</li>
<li>Maximum pool size—The maximum number of beans that can be present in the pool. The default is 32.</li>
<li>Pool resize quantity—The number of beans to be removed when the pool idle timeout expires. The default is 8.</li>
<li>Pool idle timeout—The maximum number of seconds that a bean can reside in the pool without servicing a request before it is released for garbage collection.</li>
</ul>
<p>These are only a couple of the pool settings—there are many more. The parameters available to tune a container are container specific. Thus, the containers compete on scalability and performance-tuning features. The important thing to remember is that, if you are not using stateless session beans and are implementing your homegrown solution, you want have to implement your own pooling solution and then optimize its performance. As you can see, a stateless session bean is providing a significant amount of functionality. Implementing and testing business functionality is one thing; building an efficient pooling system and testing the algorithms is a separate matter.</p>
<p>The specification for stateless session beans refers to the pool as the Method-Ready Pool. An object in the method ready pool may have instance variables storing data—there is nothing to prevent the bean from doing this. However, given that there are numerous instances and that each method invocation is potentially and randomly a different client, member variables aren’t too useful unless they are used for internal purposes. For example, a method may load a complex object into memory and then store it in a member variable. The member variable can then be accessed from utility methods that are part of a call; you invoke method A, method A then invokes protected method B, and so on. This can be very dangerous because data could leak between method calls on a stateless session bean if precautions are not taken. Pooling stateless session beans is one of their key features.</p>
<h2>Summary</h2>
<p>We discussed the mechanics of stateless session beans—how to define them and how to pool them. We’ve explained when to use a stateless session bean.</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/04/stateless-session-beans-in-ejb-3-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use CDI with EJB 3.0?</title>
		<link>http://www.javabeat.net/2011/04/using-cdi-with-ejb-3-0/</link>
		<comments>http://www.javabeat.net/2011/04/using-cdi-with-ejb-3-0/#comments</comments>
		<pubDate>Wed, 06 Apr 2011 15:13:19 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>
		<category><![CDATA[CDI]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=627</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 based on EJB3 in Action, Second Edition and the book will released on October 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When [...]</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><em>This article is based on <a href="http://www.flipkart.com/ejb-3-action-8177227327/p/itmdynbytvmduact?pid=9788177227321&amp;affid=suthukrish" target="_blank">EJB3 in Action, Second Edition </a>and the book will released on October 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.</em></p>
<p align="justify"><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2009/02/ejb-interview-questions/">EJB Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2010/10/securing-ejb-applications/">How to secure EJB applications?</a></li>
<li><a href="http://www.javabeat.net/2011/04/using-cdi-with-ejb-3-0/">Using CDI with EJB 3.0</a></li>
<li><a href="http://www.javabeat.net/j2ee-books/">J2EE Books</a></li>
</ul>
<h1 style="text-align: center;">Using CDI with EJB 3.0</h1>
<h2>Introduction</h2>
<p>CDI plays a vital role by providing robust, next-generation, annotation-driven dependency-injection to all Java EE components including EJB 3. In this article, we will show you some of the most common ways CDI is used with EJB 3—namely, as a more robust replacement to JSF-managed beans and complementing EJB with components that are not in the business tier and do not need to use EJB services directly.</p>
<h2>Using CDI with JSF 2.0 and EJB 3.0</h2>
<ul>
<li><a href="http://www.javabeat.net/2007/05/introduction-to-java-server-faces/">Introduction to JSF
<p></a></li>
</ul>
<p>In order to see how CDI can be used as the superglue between <a href="http://www.javabeat.net/2007/05/introduction-to-java-server-faces/">JSF</a> and EJB 3, let’s look at a bid service stateless session bean example. The bid service allows us to save bids into the database. Clearly, the add bid functionality would likely be used on a page that allows the bidder to place a bid on an item. If you are familiar with auction sites, this page could look something like figure 1.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/14.jpg"><img class="aligncenter size-medium wp-image-1166" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/04/14-300x156.jpg" width="300" height="156" /></a>Most of the page displays the details about the item, the bids, the seller, and the bidder such as the item title, description, highest bid, current bidders, seller information, and so on. The part we are most interested in is the text box to enter a bid amount and the button to place a new bid. The JSF 2 code for these two page elements will look like listing 1.</p>
<ul>
<li><em><a href="http://www.flipkart.com/ejb-3-action-8177227327/p/itmdynbytvmduact?pid=9788177227321&amp;affid=suthukrish" target="_blank">EJB3 in Action, Second Edition</a></em></li>
</ul>
<p><strong>Listing 1 JSF page to add bid</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;&gt;
&lt;h:body&gt;
...
&lt;h:form id=&quot;bid-form&quot;&gt;
...
&lt;h:inputText id=&quot;input-bid&quot; value=&quot;#{bid.amount}&quot;/&gt; #1
...
&lt;h:commandButton id=&quot;place-bid-button&quot; #1
value=&quot;Place Bid!&quot; #1
action=&quot;#{bidManager.placeBid}&quot;/&gt; #1
...
&lt;/h:form&gt;
...
&lt;/h:body&gt;
&lt;/html&gt;
</pre>
<p><strong>#1 Binding expressions to CDI managed beans</strong></p>
<p>As you can see, both the input text field and the button are bound to the underlying beans using binding expressions (#1). The input text field is bound to the amount field of a bean named bid. This means that the text field displays the value of the bound bean field, and any value entered into the text field is automatically set into the bean field. The place-bid button is bound to the placeBid method of a bean named bidManager. This means that the bound method is automatically invoked when the button is clicked. Listing 2 shows code that the JSF page elements are bound to.</p>
<p><strong>Listing 2 BidManager CDI managed bean</strong></p>
<pre class="brush: java; title: ; notranslate">@Named #1
@RequestScoped #2
public class BidManager {
	@Inject #3
	private BidService bidService;
	@Inject #4
	@LoggedIn #4
	private User user;
	@Inject #5
	@SelectedItem #5
	private Item item;
	private Bid bid = Bid();
	@Produces #6
	@Named #6
	@RequestScoped #6
	public Bid getBid() {
		return bid;
	}
	public String placeBid() {
		bid.setBidder(user);
		bid.setItem(item);
		bidService.addBid(bid);
		return “bid_confirm.xhtml”;
	}
}

#1 Names bid manager CDI managed bean

#2 The bid manager is request scoped

#3 Injects bid service EJB

#4 Injects currently logged-in user

#5 Injects currently selected item

#6 Produces a request-scoped CDI managed bean named 'bid'</pre>
<p>The bid manager component is not an EJB but simply a CDI-managed bean. This means that, other than life cycle, dependency injection, and context management, no enterprise services such as transaction management are available directly to the bid manager component. This is perfectly fine in this case since the bid manager simply acts as the glue between the JSF page and transactional EJB service tier.</p>
<p>As such, the bid manager is probably self-explanatory even with the various CDI annotations. The @Named CDI annotation (#1) on the bid manager names the component. By default, the component is named as the simplified class name in camel-case. In the case of the bid manager component, the name assigned will be ‘bidManager’. Naming a component is necessary in order to reference it from JSF EL. As you’ve seen, the BidManager.placeBid method is bound to the place bid button via an EL binding expression. The @RequestScoped CDI annotation (#2) specifies the scope of the bid manager. Because the bid manager is request scoped, the bean will be created when the JSF page is loaded and is destroyed when the user navigates to another page.</p>
<p>A number of other beans are injected into the bid manager component as dependencies. The first is the bid service stateless session bean (#3) we are already familiar with. The injections for the bidder (#4) and item (#5) are a bit more interesting. The @LoggedIn and @SelectedItem annotations are CDI user-defined qualifiers. Qualifiers are user-defined meta-data used to specify that you want a specific type of bean injected. For example, in case of injecting the user into the bid manager, we are specifying that we want a special kind of user—namely, the currently logged-in user. The code assumes that CDI has reference to a suitable User instance in some known accessible scope. Most likely, the User bean corresponding to the logged-in user is in the session scope and was placed there as part of the login process. Similarly, the bid manager code uses the @SelectedItem qualifier to specify that it depends on the item that the user has currently selected. The selected Item bean was likely placed into the request scope when the user clicked on the link to view the item details.</p>
<p>The @Produces, @RequestScoped, and @Named annotations (#6) placed on the getBid method are very interesting as well. As you may have guessed, the @Produces annotation is a key piece of functionality. The @Produces annotation tells CDI that the getBid method returns a Bid object that it should manage. The @Named and @RequestScoped annotations on the getBid method tells CDI that the returned Bid object should be named and it should be in the request scope. Because the bid object is named, it can be reference in EL just as we did in the JSF page. It is a JPA 2 entity that holds all bid data, including the bid amount that is bound by EL to the input text field on the JSF page. Because the bid manager creates and holds a reference to the bid object, it automatically has access to the bid data entered via the JSF page.</p>
<p>When the placeBid method is invoked in response to the button-click on the JSF page, the bid manager uses all the data it has reference to and properly populates the bid object. It then uses the bid service stateless session to have the bid into the database. Finally, the user is redirected to a page that confirms the bid.</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>That is all that we need to say about using CDI with EJB 3 at the presentation tier at the moment. CDI is used with EJB 3 in a number of other different ways, including at the persistence tier to implement DAOs. Let’s take a look at that next.</p>
<h2>Using CDI with EJB 3.0 and JPA 2.0</h2>
<p>In Java EE 5-based systems, the DAO layer is often implemented as EJB 3 beans. This technique makes a certain amount of sense, especially if the DAO is marked with the ‘transaction required” attribute. This forces all clients that use the DAOs to handle transactions and is a great safeguard since DAOs often utilize resources that require transactions such as the database. However, for in-house applications where the service and DAO layers are often developed by the same team, these safeguards are not always needed. In fact, it is possible to develop DAOs using plain CDI managed beans and inject them into EJBs at the service tier. To see what the code looks like, let’s check out the bid manager stateless session bean in listing 3.</p>
<p><strong>Listing 3 BidService stateless session bean code</strong></p>
<pre class="brush: java; title: ; notranslate">@Stateless #A
public class DefaultBidService implements BidService {
	@Inject #B
	private BidDao bidDao;
	...
	public void addBid(Bid bid) {
		bidDao.addBid(bid);
	}
	...
	}
	@Local
	public interface BidService {
	...
	public void addBid(Bid bid);
	...
	}</pre>
<p><strong>#A Marks POJO as stateless session bean</strong></p>
<p><strong>#B Injects non-EJB DAO</strong></p>
<p><strong>#C Marks interface as local</strong></p>
<p>The bid DAO injected into the EJB is a CDI managed bean with an interface. The DAO relies on the transaction and thread-safety context of the EJB and does not need to have any services other than basic dependency injection offered by CDI. Any other services such as security and asynchronous processing are also likely best applied at the service tier rather than the persistence tier. Listing 4 shows the code for the DAO.</p>
<p><strong>Listing 4 BidDao CDI managed bean</strong></p>
<pre class="brush: java; title: ; notranslate">public class DefaultBidDao implements BidDao {
	@PersistenceContext #A
	private EntityManager entityManager;
	...
	public void addBid(Bid bid) {
		entityManager.persist(bid);
	}
	...
	}
	public interface BidDao {
	...
	public void addBid(Bid bid);
	...
	}</pre>
<p><strong>#A Injects the JPA 2 entity manager</strong></p>
<p>As such, the DAO is very simple. In fact, some of you might be surprised that neither the DAO class nor the interface has any annotations on it at all. This is really quite normal in the CDI world since CDI-managed beans truly are bare POJOs. When CDI sees the @Inject annotation in the bid service EJB, it simply looks for any object that implements the BidDao interface and injects it. It is important to note that the bid DAO is nameless—it does not have an @Named annotation. This is because the DAO really does not need to be referenced by name anywhere. The DAO also does not have a defined scope. When this happens, CDI assumes that the bean belongs in the default scope. By default, CDI creates a brand new instance of the bean and injects it into the dependent component—basically the same behavior as a “new” operator at the injection point. Notice also that the bid DAO itself can request injection as well. In the example, CDI injects a JPA 2 entity manager into the DAO that is used to save the bid entity into the database.</p>
<p>The CDI features you saw in this article are truly the tip of the iceberg. CDI has a vast array of other features like stereotypes, events, interceptors, and decorators.</p>
<h2>Summary</h2>
<p>We showed you what to expect from the new version of the Java enterprise platform, specifically, how CDI and EJB 3 work together seamlessly across application tiers.</p>
<p align="justify"><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2009/02/ejb-interview-questions/">EJB Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2010/10/securing-ejb-applications/">How to secure EJB applications?</a></li>
<li><a href="http://www.javabeat.net/2011/04/using-cdi-with-ejb-3-0/">Using CDI with EJB 3.0</a></li>
<li><a href="http://www.javabeat.net/j2ee-books/">J2EE Books</a></li>
</ul>
<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/04/using-cdi-with-ejb-3-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Managing transactions in EJB 3.0</title>
		<link>http://www.javabeat.net/2010/11/managing-transactions-in-ejb-3-0/</link>
		<comments>http://www.javabeat.net/2010/11/managing-transactions-in-ejb-3-0/#comments</comments>
		<pubDate>Mon, 29 Nov 2010 01:26:53 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=522</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>Transaction represents a group of activities that must be performed as a single work unit. This clarifies that a transaction is complete if and only if all the work items within a work group results in success. If any of the work items fails, then the transaction as a whole will be treated as a [...]</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 align="justify">Transaction represents a group of activities that must be performed as a single work unit. This clarifies that a transaction is complete if and only if all the work items within a work group results in success. If any of the work items fails, then the transaction as a whole will be treated as a failure. Managing transactions is vital not only for Enterprise applications but also for any flavour of applications. In this article we will explore the various services provided by the <strong>EJB</strong> container with respect to transaction management. This article assumes that the reader has a basic understanding on <strong>EJB</strong> technology such the various <strong>EJB</strong> containers, enterprise beans etc along with the fundamental concepts of transactions such as ACID properties, commit and rollback.</p>
<p align="justify"><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2009/02/ejb-interview-questions/">EJB Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2010/10/securing-ejb-applications/">How to secure EJB applications?</a></li>
<li><a href="http://www.javabeat.net/2011/04/using-cdi-with-ejb-3-0/">Using CDI with EJB 3.0</a></li>
<li><a href="http://www.javabeat.net/j2ee-books/">J2EE Books</a></li>
</ul>
<h2>Download Source Code</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/sourcecode/2010/201011-managing-transactions.zip">Transactions in EJB 3.0 Sample Code</a></li>
</ul>
<h2>Container managed transactions in EJB 3.0</h2>
<p align="justify">It is possible for applications to provide an indication that the transactions can be managed by the Container. Such transactions which are not managed through the application&#8217;s code but through the container are called Container managed transactions. It is the responsibility of the application developer to specify the transaction demarcation through transactional attributes. This information can be specified either through Annotations or through the configuration file. Note that specifying the transactional metadata through annotations is not available until the version 3.</p>
<h3>Transactional Attributes</h3>
<p align="justify">Container managed transactions are supported through various transactional attributes. The available transactional attributes are as follows</p>
<ul>
<li>Required</li>
<li>Requires New</li>
<li>Supports</li>
<li>Not Supported</li>
<li>Mandatory</li>
<li>Never</li>
</ul>
<h4>Required</h4>
<p align="justify">This is the default attribute if the transactional attribute is not specified. This indicates to the container that the annotated business method has to execute within a transaction. More specifically, when there is an active transaction, and if a business method is called from within the active transaction, then the method executes as if it is part of the transaction. This means that the success or the failure of the transaction will be propagated to this transaction. When the caller is not part of a transaction, then a new transaction is started. Consider the following code snippet,</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.required;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class EmployeeDetailBean implements EmployeeDetailLocal {

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void createEmployeeDetail() {

    }
}</pre>
<p align="justify">In the above enterprise bean definition, we have annotated the method createEmployeeDetail() with the &#8216;Required&#8217; annotation. This business method will be called from the EmployeeBean which is defined below.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.required;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class EmployeeBean implements EmployeeLocal {

    @EJB
    private EmployeeDetailLocal employeeDetailBean;

    public void createEmployee() {
        // Create employee here
        employeeDetailBean.createEmployeeDetail();
    }
}</pre>
<p align="justify">As we can see in the createEmployee() method, the employee object is expected to be created first followed by the creation of employee detail object. Now if there is exception before the return of the business method &#8216;createEmployee()&#8217; then the employee detail object won&#8217;t be created.</p>
<h4>Requires New</h4>
<p align="justify">The transactional attribute &#8216;Requires New&#8217; will also start a new transaction irrespective of the fact that the caller is in active transaction or not. This attribute can be applied to business methods where the result of the calling transaction is not dependent on the business method that is annotated with &#8216;Requires New&#8217;.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.requiresnew;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DepartmentBean implements DepartmentBeanRemote {

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void createDepartment() {
    }
}</pre>
<p align="justify">Considering the above example, we have a business method that creates a department object and the method is annotated with the transactional attribute &#8216;Requires New&#8217;. Now consider the below code,</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.requiresnew;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class EmployeeBean implements EmployeeBeanRemote {

    @EJB
    private DepartmentBeanRemote departmentBean;

    public void createEmployee() {
        // Create employee object here
        departmentBean.createDepartment();
       // Assign the newly created department object to the employee object
    }
}</pre>
<p align="justify">Here after creating the employee object, we call the enterprise bean for creating a department. Let us assume that we a creating a new employee object and during the course of creation, we also want to create a new department object and assign it to the employee object. Now imagine a transactional failure before the return of the method createEmployee(), in which case, the creation of the department won&#8217;t be rolled back because the department creation process is in a separate transaction. This also means that when we create a different employee object we can assign this employee object to the already created department object.</p>
<h4>Supports</h4>
<p align="justify">The transactional attribute &#8216;Supports&#8217; defines that the transactional mode has to be propagated from the caller to the business method that is annotated with &#8216;Supports&#8217;. This means that if the caller is in an active transaction, then the business method will also execute as part of the active transaction. This means that a failure in the business method will revert the caller&#8217;s transaction also. If the caller is not part of the transactional context, then the business method will also execute in a non-transactional context.</p>
<h4>Not Supported</h4>
<p align="justify">This transactional attribute can be used for scenarios where a part of the business operation shouldn&#8217;t be executed in a transactional context at all. If the caller is part of the transaction, then the caller&#8217;s transaction is suspended and resumed once the execution of the business method that is annotated with &#8216;Not Supports&#8217; is completed. If the caller is not part of any transaction, then also the business method will execute outside the transactional context.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.requiresnew.notsupported;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class MailSenderBean implements MailSenderLocal {

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void sendMail() {
    }

}</pre>
<p align="justify">In the above example, we have modeled a simple sessionbean that sends a mail. Let us assume that this bean will be used as part of some user registration process. That is, once the user is registered, the application will try to send a mail by calling this enterprise bean. Because the operation of sending a mail to the customer can&#8217;t be part of a transaction, the method is annotated with &#8216;Not Supported&#8217;. Have a look at the caller&#8217;s code.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.requiresnew.notsupported;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class UserRegistrationBean implements UserRegistrationLocal {

    @EJB
    private MailSenderLocal mailSenderBean;

    public void registerUser() {

        // Do user registration here
        mailSenderBean.sendMail();
    }
}</pre>
<h4>Mandatory</h4>
<p align="justify">The transactional attribute &#8216;Mandatory&#8217; can be used when we wanted to make sure that some business method has to be executed as part of a transaction. If the caller&#8217;s code is not part of the transaction, then an exception will be thrown. Have a look at the below code.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.mandatory;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class MoneyTransferBean implements MoneyTransferLocal {

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void transferMoney() {

        deductMoneyFromSource();
        addMoneyToDestination();
    }

    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public void deductMoneyFromSource() {
    }

    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public void addMoneyToDestination() {
    }
}</pre>
<p align="justify">We have defined three business methods &#8216;transferMoney&#8217;, &#8216;deductMoneyFromSource&#8217; and &#8216;addMoneyToDestination&#8217;. If we assume that the business method &#8216;deductMoneyFromSource&#8217; and &#8216;addMoneyToDestination&#8217; should be part of some transactional method &#8216;transferMoney&#8217;, then these methods have to be annotated with &#8216;Mandatory&#8217; annotation. This ensures that the business methods &#8216;deductMoneyFromSource&#8217; and &#8216;addMoneyToDestination&#8217; cannot be and shouldn&#8217;t be executed from a non-transactional environmental context.</p>
<h4>Never</h4>
<p align="justify">This is a rarely used transactional attribute as an exception will be thrown if a caller, as part of an active transaction, executes a business method that is annotated with &#8216;Never&#8217;.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.container.never;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DataLoaderBean implements DataLoaderLocal {

    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void loadDataFromXml(String xmlFilename) {
    }

    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void loadDataFromFlatFile(String filename) {
    }

}</pre>
<p align="justify">In the above example, we have business methods for loading data from a non-transactional data resource such as the file system. Hence we have given the transactional attribute as &#8216;Never&#8217;.</p>
<h3>Bean Managed transactions in EJB 3.0</h3>
<p align="justify">Now that we have seen the advantages and the usage of CMT, let&#8217;s see where and how to use Bean Managed Transactions. Even though it is quite uncommon, still there are scenarios where customizations with respect to transaction handling might be required at the application level. The level of customization include when to begin a transaction in a business method, when to commit a transaction by defining a successful scenario and when to rollback a transaction for a failure scenario. For example consider the sample code,</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.bean;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.transaction.UserTransaction;

@TransactionManagement(value=TransactionManagementType.BEAN)
@Stateless
public class BillPaymentBeanBean implements BillPaymentBeanLocal {

    @Resource
    private UserTransaction userTransaction;

    public void payBill() throws Exception{

        try{
            userTransaction.begin();

            provideBillDetailsInfo();
            identifyCustomerAccount();
            makeBillPayment();

            userTransaction.commit();
        }catch (IncorrectBillDetailsException exception){
            userTransaction.rollback();
        }catch (InvalidCustomerAccountException exception){
            userTransaction.rollback();
        }catch (PaymentException exception){
            userTransaction.rollback();
        }
    }

    private void identifyCustomerAccount()
        throws InvalidCustomerAccountException {
    }

    private void makeBillPayment() throws PaymentException{
    }

    private void provideBillDetailsInfo()
        throws IncorrectBillDetailsException{
    }
}</pre>
<p align="justify">The first obvious thing to be noted in BMT is that we have to use @TransactionManagement(BEAN) to instruct the container that we are using Bean managed transactions for this enterprise bean. The above example shows how to use BMT with the help of UserTransaction interface. UserTransaction provides a single entry point for managing bean managed transactions and to obtain a valid reference to this interface, the annotation @Resource can be used. This makes sure that the container populates the UserTransaction reference and makes it available. To signal the logical beginning of a transaction, the method begin() can be used. Similarly there are commit() and rollback() signaling that the transaction is successful or failure respectively. Note that in the above example case, whenever we encounter a exception scenario, we indicate that the transaction is a failure by calling the rollback() method. The code snippet for the related exception classes are given below.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.txnmgmt.bean;
public class IncorrectBillDetailsException extends Exception{
}

package net.javabeat.articles.ejb.txnmgmt.bean;

public class InvalidCustomerAccountException extends Exception {
}

package net.javabeat.articles.ejb.txnmgmt.bean;

public class PaymentException extends Exception{

}</pre>
<h2>Handling Exceptions in EJB 3.0</h2>
<p align="justify">It is important to understand the effect of exceptions when dealing with transactional business methods. In the context of Enterprise beans, exceptions can be either classified as System Exception or Application Exception.</p>
<h3>System Exception</h3>
<p align="justify">The default behaviour of the EJB Container is to rollback the transaction whenever a System exception occurs. Any Exception that is a subclass of RuntimeException or RemoteException will be classified and treated as a System exception. This is the default exception handling when the transaction is managed by the container. When a system error is encountered, the calling client will always perceive that exception as a instance of EJBException or RemoteException. However in the case of Bean managed transactions, it is upto the application as how to handle the system exception, though it is considered as a bad programming practice to catch a system exception and not performing a rollback. For example, consider the following code snippet</p>
<pre class="brush: java; title: ; notranslate">@Resource
private UserTransaction transaction;
public void someBizMethod(){

	try{
		transaction.begin();
	}catch (NullPointerException npe){
		transaction.commit();
	}
}</pre>
<p align="justify">In the above exception, even through NullPointerException is a system exception (because NullPointerException is an instance of RuntimeException), we are making a commit by calling the transaction&#8217;s commit() method.</p>
<h3>Application Exception</h3>
<p align="justify">Application exceptions are generally thrown when the attempt is made to execute a business method results in an error because during the course of the execution it is identified that some business logic went wrong. For example, while performing money transfer between two accounts it is mandatory that sufficient funds have to be present in the source account. An application error can be thrown during the execution of this business method because of insufficient funds. By default when an application error is thrown, the container won&#8217;t rollback the transaction as opposed to System exceptions. Also the exception will be reached its client in its regular form, i.e unlike System exceptions, where the source of the exception will be wrapped as either EJBException or RemoteException.</p>
<p align="justify">There can be cases where we want to make the transaction rollback for an application exception. In the case of a Bean managed transaction, this scenario is straight-forward, as the application has the control over the UserTransaction. Rolling the transaction would be as simple to call the method rollback(). However, in the case of the Container managed transactions, the situation becomes quite tricky and the annotation @ApplicationException comes to the rescue. For example, let us consider that in the example of money transfer, if sufficient amount is not available in the source account, then we want to throw a customized exception called InsufficientFundsException and also to rollback the transaction.</p>
<pre class="brush: java; title: ; notranslate">@ApplicationException(rollback=true)
public class InsufficientFundsException extends Exception{
	public InsufficientFundsException(String message){
	}
}</pre>
<p align="justify">In the above code snippet, we have created a customized exception along with the annotation Application Exception with the attribute rollback set to true. This ensures that for a business method, that declares this exception at the throws clause, when this exception is encountered during the execution of the business operation, the container will request for a transaction rollback.</p>
<h2>Persistence Context and Entity Manager</h2>
<p align="justify">Closely associated with EJB transactions are Entity Manager and Persistence Contexts. Entity Manager is an interface for managing entites whereas Persistence Context is an annotation that can be applied on Entity Manager instances. The annotation has name, persistence unit name and type. The persistence unit name, if specified has to match the unit name that is defined in the persistence.xml file. Persistence context can either be transaction scoped or extended scoped. If the persistence context operates in transaction scope, then it means that the entities that are associated with the persistence context have the life-time equal to that of the transaction. That is, when the transaction ends, any changes done to the entities wont get notified to the persistence context. However, in the case of the extended persistence context, the entities will be attached to the persistence context even after the completion of the transaction. The entities will be detached from the persistence context only when the method close() is called on the Entity Manager object.</p>
<p align="justify">Consider the following piece of code,</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb.transactions.application;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class ApplicationFacade implements ApplicationFacadeRemote {

    @PersistenceContext
    private EntityManager em;

    public void create(Application application) {
        em.persist(application);
    }

    public void edit(Application application) {
        em.merge(application);
    }

    public void remove(Application application) {
        em.remove(em.merge(application));
    }

    public Application find(Object id) {
        return em.find(Application.class, id);
    }

    public List findAll() {
        return em.createQuery(&quot;select object(o) from Application as o&quot;).getResultList();
    }
}</pre>
<p align="justify">Note that the entity manager reference is injected by the container as it is annotated with <em>@PersistenceContext</em> annotation. If the persistent unit name is not specified as part of the annotation, then by default, the file name persistence.xml will be looked up for finding the persistence name. The contents of the <em>persistence.xml</em> is given below,</p>
<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;Application-ejbPU&quot; transaction-type=&quot;JTA&quot;&gt;
    &lt;provider&gt;oracle.toplink.essentials.PersistenceProvider&lt;/provider&gt;
    &lt;jta-data-source&gt;new&lt;/jta-data-source&gt;
    &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt;
    &lt;properties&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>
<h2>Conclusion</h2>
<p align="justify">This article started by exploring the various techniques of managing transactions in an <strong>EJB</strong> environment – namely the Container Managed transactions and Bean managed transactions. The various transactional attributes that are applicable for contained managed transactions are given a healthier discussion under the section &#8216;Transactional attributes&#8217;. Also for easier understanding, many sample code snippets were presented for illustration. Then the article went on with discussing the usage the Bean managed transactions. Because it is essential to understand the impact of exception handling with respect to transactions, the final section of the article explained the exception handling mechanisms for System Exceptions and Application Exceptions.</p>
<p align="justify"><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/2009/02/ejb-interview-questions/">EJB Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2010/10/securing-ejb-applications/">How to secure EJB applications?</a></li>
<li><a href="http://www.javabeat.net/2011/04/using-cdi-with-ejb-3-0/">Using CDI with EJB 3.0</a></li>
<li><a href="http://www.javabeat.net/j2ee-books/">J2EE Books</a></li>
</ul>
<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/11/managing-transactions-in-ejb-3-0/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Building an EJB 3.0 Persistence Model with Oracle JDeveloper</title>
		<link>http://www.javabeat.net/2010/09/building-an-ejb-3-0-persistence-model-with-oracle-jdeveloper/</link>
		<comments>http://www.javabeat.net/2010/09/building-an-ejb-3-0-persistence-model-with-oracle-jdeveloper/#comments</comments>
		<pubDate>Sun, 05 Sep 2010 23:51:04 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1813</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>EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g EJB (Enterprise JavaBeans) 3.0 entity beans is a commonly used database persistence technology. EJB 3.0 has simplified the development of EJBs with an annotations-based APithat does not require remote/local interfaces, home/local home interfaces, or deployment descriptors. Developing entity EJBs requires an application server and a relational [...]</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><H1><CENTER><b>EJB 3.0</b> Database Persistence with Oracle Fusion Middleware 11g</CENTER></H1><br />
<P>EJB (Enterprise JavaBeans) 3.0 entity beans is a commonly used database persistence<br />
technology. <b>EJB 3.0</b> has simplified the development of EJBs with an annotations-based<br />
APithat does not require remote/local interfaces, home/local home interfaces, or<br />
deployment descriptors. Developing entity EJBs requires an application server and a<br />
relational database, and optionally a Java EE IDE to simplify the process of development.<br />
The objective of the JSR-000220 Enterprise JavaBeans 3.0 specification (</p>
<p>http://jcp.org/aboutJava/communityprocess/final/jsr220/index.html)</p>
<p>is to improve the EJB architecture by reducing its complexity from the developer&#8217;s point<br />
of view. <b>EJB 3.0</b> has introduced some new features, which include support for metadata<br />
annotations, default values for configuration, simplified access to environment variables,<br />
simplified session and entity beans, interceptors, enhanced support for checked<br />
exceptions, and elimination of callback interfaces.</P><br />
<P>A number of books are available on <b>EJB 3.0</b>, but none cover <b>EJB 3.0</b> on the Oracle<br />
Fusion Middleware (11<I>g</I>) platform. Most of the <b>EJB 3.0</b> books are GlassFish server<br />
based, which has only 10percent of the application server market. Welcome to <I><b>EJB 3.0</b><br />
Database Persistence with Oracle Fusion Middleware 11g</I>, a book that will teach you<br />
how to leverage <b>EJB 3.0</b> persistence on Oracle Fusion Middleware 11<I>g</I>. Oracle Fusion<br />
Middleware 11<I>g</I> includes many components such as the SOA/BPM Suite, WebCenter,<br />
and Oracle Identity Management. All of these components run on Oracle Weblogic<br />
Server 11<I>g</I>. The main development tool (IDE) for Oracle Fusion Middleware is Oracle<br />
JDeveloper. In respect of <b>EJB 3.0</b>, JDeveloper provides wizard support to reverse<br />
engineer database tables as <b>EJB 3.0</b> entity beans. JDeveloper 11<I>g</I> also provides a wizard<br />
for creating session beans. The <b>JPA</b> persistence provider used in JDeveloper 11g is the<br />
EclipseLink persistence provider. JDeveloper comes with its own embedded/integrated<br />
Weblogic Server instance, which makes it very easy to develop and test within the one<br />
environment. We shall be using the embedded WebLogic Server 11<I>g</I> in some of the<br />
chapters and the standalone WebLogic Server in others.</P><br />
<P>The objective of the book is to discuss the support of <b>EJB 3.0</b> database persistence in<br />
Oracle Fusion Middleware 11g. While JDeveloper is the main Java IDE used in the book,<br />
one of the chapters leverages the Oracle Enterprise Pack for Eclipse. The book covers all<br />
aspects of <b>EJB 3.0</b> database persistence including:</P><br />
<UL><br />
<LI>Creating <b>EJB 3.0</b> entity beans from database tables</LI><br />
<LI>Creating session bean façades for entity beans</LI><br />
<LI>Entity beans with session beans</LI><br />
<LI>Creating <b>EJB 3.0</b> entity relationships</LI><br />
<LI>Creating JSF and ADF Faces user interfaces (UIs) on top of <b>EJB 3.0</b><br />
database persistence</LI><br />
<LI>Using <b>EJB 3.0</b> database persistence in combination with Ajax and web services</LI><br />
</UL></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>
<h2>EJB 3.0 Articles</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/81-jpa-in-netbeans-61-1.html">JPA in NetBeans 6.1</a></li>
<li><a href="http://www.javabeat.net/articles/80-ejb-30-and-webservices-1.html">EJB 3.0 and WebServices</a></li>
<li><a href="http://www.javabeat.net/articles/5-introduction-to-java-persistence-apijpa-1.html">Introduction to Java Persistence API(JPA)</a></li>
<li><a href="http://www.javabeat.net/articles/3-ejb-30-timer-services-an-overview-1.html">EJB 3.0 Timer Services &#8211; An Overview</a></li>
</ul>
<p><H1>What This Book Covers</H1><br />
<P>In Chapter 1, What&#8217;s New in <b>EJB 3.0</b>, we discuss the new features in the <b>EJB 3.0</b><br />
specification, such as support for metadata annotations, default values for configuration,<br />
simplified session and entity beans, and enhanced support for checked exceptions.</P><br />
<P>In Chapter 2, Converting an EJB 2.0 Entity to an EJB, we convert an example EJB 2.0<br />
entity bean to an <b>EJB 3.0</b> entity bean. We also generate the session bean façade for the<br />
<b>EJB 3.0</b> entity bean. XSLT transformation is used for converting the EJB 2.0 entity bean<br />
to an <b>EJB 3.0</b> entity bean.</P><br />
<P>In Chapter 3, EclipseLink <b>JPA</b> Persistence Provider, we discuss the <b>JPA</b> framework and<br />
the EclipseLink persistence provider.</P><br />
<P>In Chapter 4, Building an <b>EJB 3.0</b> Persistence Model with Oracle JDeveloper, we discuss<br />
<b>EJB 3.0</b> database persistence with JDeveloper 11g, WebLogic Server 11g, and Oracle<br />
Database 10g. We create an <b>EJB 3.0</b> entity bean from a database table, create a session<br />
bean façade, and finally create a <i>JSP</i> test client. Using the test client, we create, retrieve,<br />
and delete entity bean instances.</P><br />
<P>In Chapter 5, <b>EJB 3.0</b> Persistence with Oracle Enterprise Pack for Eclipse, we discuss the<br />
same example we covered in Chapter 4, but with the Oracle Enterprise Pack for Eclipse,<br />
WebLogic Server, and the open source MySQL database, which has been acquired by<br />
Oracle.</P><br />
<P>In Chapter 6, <b>EJB 3.0</b> with ADF Faces UI, we discuss using an ADF Faces client for EJB<br />
3.0 database persistence. We create an entity bean using data input from an ADF Faces<br />
user interface (UI). Subsequently, we find an entity bean instance using data input from<br />
an ADF Faces UI.</P><br />
<P>In Chapter 7, Creating <b>EJB 3.0</b> Entity Relationships, we discuss <b>EJB 3.0</b> entity<br />
relationships using, as an example, three entity beans that have inter-relationships. We<br />
also discuss the significance of a fetch strategy.</P><br />
<P>In Chapter 8, <b>EJB 3.0</b> Database Persistence with Ajax in the UI, we discuss <b>EJB 3.0</b><br />
database persistence in combination with Ajax in the user interface (UI). We demonstrate<br />
data validation and autocompletion with Ajax.</P><br />
<P>In Chapter 9, Using JSF with Entity Relationships, we discuss adding JSFs to <b>EJB 3.0</b><br />
database persistence to create and persist entity bean instances that have entity<br />
relationships between them.</P><br />
<P>In Chapter 10, Creating an <b>EJB 3.0</b> Web Service, we create a JAX-WS Web Service from<br />
an <b>EJB 3.0</b> entity bean, create a web service client, package and deploy the web service<br />
to WebLogic Server, and test the Web Service using the WebLogic console.</P><br />
<H1><CENTER>Building an <b>EJB 3.0</b> Persistence Model with Oracle JDeveloper</CENTER></H1><br />
<P>Oracle Fusion Middleware is a family name for a set of Java EE products that are<br />
integrated for SOA and web application deployment. <B>WebLogic Server (WLS)</B> is the<br />
Java EE container and Oracle JDeveloper the Java EE and SOA development IDE.<br />
In this chapter, we will use JDeveloper to create an <b>EJB 3.0</b> application, and then we<br />
will deploy and test our application leveraging the embedded WebLogic Server that<br />
comes with JDeveloper. This makes it very easy for us to develop, deploy, and test<br />
our application.</P><br />
<P>WebLogic server 10.x provides some value-added features to facilitate EJB<br />
3 development. WebLogic server 10.x supports automatic deployment of a<br />
persistence unit based on the injected variable&#8217;s name. The @javax.persistence.<br />
PersistenceContext and @javax.persistence.PersistenceUnit<br />
annotation s are used to inject the persistence context in an EntityManager or<br />
EntityManagerFactory variable . A persistence context is a set of entities that are<br />
mapped to a database with a global JNDiname. If the name of the injected variable<br />
is the same as the persistence unit, the unitName attribute of the<br />
@PersistenceContext or @PersistenceUnit is not required to be specified. The<br />
EJB container automatically deploys the persistence unit and sets its JNDiname to<br />
be the same as the persistence unit name in persistence.xml. For example, if the<br />
persistence unit name in the persistence.xml file is em, an EntityManager variable<br />
may be injected with the persistence context as follows:</P><br />
<P><PRE><CODE><br />
	@PeristenceContext<br />
	private EntityManager em;<br />
</CODE></PRE></P><br />
<P>We did not need to specify the unitName attribute in the @PersistenceContext<br />
because the variable name is the same as the persistence unit. Similarly, an<br />
EntityManagerFactory variable may be injected with the persistence context as<br />
follows, emf being also the persistence unit name:</P><br />
<P><PRE><CODE><br />
	@PersistenceUnit<br />
	private EntityManagerFactory emf;<br />
</CODE></PRE></P><br />
<P>Another value-added feature in WebLogic server 10.x is support for vendor-specific<br />
subinterfaces of the EntityManager interface . For example, the BEA Kodo persistence<br />
provider provides the KodoEntityManager subinterface , which may be injected with<br />
the persistence context as follows:</P><br />
<P><PRE><CODE><br />
	@PersistenceContext<br />
	private KodoEntityManager em;<br />
</CODE></PRE></P><br />
<H1>Setting the environment</H1><br />
<P>Before getting started, we need to install Oracle JDeveloper 11<I>g</I>, which may be<br />
downloaded from http://www.oracle.com/technology/products/jdev/index.<br />
html. Download the Studio Edition, which is the complete version of JDevloper<br />
with all the features. Oracle JDeveloper 11g is distributed as a GUiself-extractor<br />
application. Click on the jdevstudio11110install application. The Oracle Installer<br />
gets started. Click on <B>Next</B> in the Oracle Installer. Choose a middleware home<br />
directory and click on <B>Next</B>.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/1.jpg"/></CENTER></P><br />
<P>Choose the <B>Install Type</B> as <B>Complete</B>, which includes the integrated WebLogic<br />
Server, and click on <B>Next</B>.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/2.jpg"/></CENTER></P><br />
<P>Confirm the default <B>Product Installation</B> directories and click on <B>Next</B>.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/3.jpg"/></CENTER></P></p>
<p>The WebLogic Server installation directory is the wlserver_10.3 folder within<br />
the middleware home directory. Choose a shortcut location and click on <B>Next</B>.<br />
The <B>Installation Summary</B> lists the products that are installed, which include the<br />
WebLogic Server and the WebLogic JDBC drivers. Click on <B>Next</B> to install Oracle<br />
JDeveloper 11<I>g</I> and the integrated WebLogic Server 10.3.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/4.jpg"/></CENTER></P><br />
<P>We also need to install the Oracle database 10g/11g or the lightweight Oracle XE ,<br />
which may be downloaded from http://www.oracle.com/technology/software/<br />
products/database/index.html. When installing Oracle database, also install the<br />
sample schemas.</P><br />
<H1>Creating a datasource in JDeveloper</H1><br />
<P>Next, we create a JDBC datasource in JDeveloper. We shall use the datasource in the<br />
<b>EJB 3.0</b> entity bean for database persistence. First, we need to create a database table<br />
in some sample schema, OE for example. Run the following SQL script in SQL *Plus:</P><br />
<P><PRE><CODE><br />
	CREATE TABLE Catalog (id INTEGER PRIMARY KEY NOT NULL, journal<br />
	VARCHAR(100), publisher VARCHAR(100), edition VARCHAR(100), title<br />
	VARCHAR(100), author VARCHAR(100));<br />
</CODE></PRE></P><br />
<P>A database table gets created in the OE sample schema.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/5.jpg"/></CENTER></P><br />
<P>Next, we need to create a JDBC connection in JDeveloper with Oracle database. Open<br />
the <B>Database Navigator</B> or select the <B>Database Navigator</B> tab if already open. Rightclick<br />
on the <B>IDE Connections</B> node and select <B>New Connection</B>.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/6.jpg"/></CENTER></P><br />
<P>In the <B>Create Database Connection</B> window, specify a <B>Connection Name</B>, select<br />
<B>Connection Type</B> as <B>Oracle (JDBC)</B>, specify <B>Username</B> as <B>OE</B>, which is the schema<br />
in which the Catalog table is created, and specify the password for the <B>OE</B> schema.<br />
Select <B>Driver</B> as <B>thin</B>, <B>Host Name</B> as <B>localhost</B>, <B>SID</B> as <B>ORCL</B>, and <B>JDBC Port</B> as<br />
<B>1521</B>. Click on the <B>Test Connection</B> button to test the connection. If the connection<br />
gets established, click on <B>OK</B>.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/7.jpg"/></CENTER></P><br />
<P>The <B>OracleDBConnection</B> gets added to the <B>Database Navigator</B> view. The<br />
<B>CATALOG</B> table that we created is listed in the <B>Tables</B>.</P><br />
<P><CENTER><IMG SRC="images/2010/09/Oracle-Jdeveloper/8.jpg"/></CENTER></P></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/09/building-an-ejb-3-0-persistence-model-with-oracle-jdeveloper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Annotations and Dependency Injection in EJB 3.0</title>
		<link>http://www.javabeat.net/2009/02/annotations-and-dependency-injection-in-ejb-3-0/</link>
		<comments>http://www.javabeat.net/2009/02/annotations-and-dependency-injection-in-ejb-3-0/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 15:49:15 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=414</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 presents two important new features of EJB 3.0 which is bundeled with Java EE 5.0 specification, which are Annotations and Dependency Injection. The solid reason for this artice is , it will give us an idea how these features are used, so on their encounter in other articles of EJB3.0, we can understand [...]</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 presents two important new features of <strong>EJB 3.0</strong> which is bundeled with <strong>Java EE 5.0</strong> specification, which are <strong>Annotations and Dependency Injection</strong>. The solid reason for this artice is , it will give us an idea how these features are used, so on their encounter in other articles of EJB3.0, we can understand their functionality. So we can say learning this article will give us a smooth drive in later other EJB 3.0 core concepts. So now we are going to start to see how <em>Annotations and Dependency Injection</em> has made the life of a developer easier and code more simple and managable.</p>
<h2>Annotatons in EJB 3.0</h2>
<p><strong>Annotations</strong> came into existence with Java 5.0. <strong>Annotations</strong> essentially allow us to attatch some additional information to a Java class, interface,methods and variables. The additional information that we supply can be used by development environments like Eclipse, Java compiler, a deployment tool, a persistence provider like Hibernate or a runtime environment like the Java EE container. So, annotations can be called custom java modifiers (in addition to public final, static etc.) that can be used by anything handling java source code (like java compiler) or byte code(like java runtime environment, j2ee container ).</p>
<p>In fact, annotations are used to affect the way programs are treated mostly by tools. These tools use these annotations applied in program to produce derived files.</p>
<ul>
<li>Tools are- compiler, IDE (Integreated Development Environment), Runtime tools like(J2ee container etc.).</li>
<li>Derived files are :- New Java code, deployment descriptor, class files.</li>
</ul>
<p>In <strong>EJB 3.0</strong> annotations are used to give our components &#8220;configuration metadata&#8221; that &#8220;configuration metadata&#8221; in earlier version EJB 2.0 we used to give by way of <em>Deployment Descriptor</em>. So, use of annotations eliminates the need of XML based Deployment Descriptor (exceptions are there like Default Listener as we will see can be configured only through Deployment Descriptor not by using annotation). Annotations provide us or benifit us by</p>
<ul>
<li>Declarative Programming</li>
<li>Less coding since tool will generate the boliler plate code from annotations in the source code</li>
</ul>
<p><strong>Simple Example</strong></p>
<pre class="brush: java; title: ; notranslate">///Annotation Example on Java 5.0 to understand what is it and how it can be utilised...
//annotation interface
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)

public @interface ObjColor
{
	String minecolor() default &quot;Red&quot;;
}
.......
// plain interface
public interface Bounceable
{
  public void bounce();
}
	.....
// Class using plain interface and annotation
@ObjColor(minecolor=&quot;Yellow&quot;)
public class Ball implements Bounceable
{
  public void bounce(){
	String ballColor=Ball.class.getAnnotation(ObjColor.class).minecolor();//getting the value of minecolor element of ObjColor annotation
  System.out.println(&quot;Hey, I am a Ball , I implement Bounceable interface &quot;+
  &quot;so now I can bounce...Can you see some information has been attached to me&quot;+
  &quot; which is neither extended nor implemented , and &quot;+
  &quot;for this no new field or mathod has been added&quot;+
  &quot;professional calls it Annotation and says i can use it ...&quot;+
  &quot;and color of mine is &quot;+ballColor);
}
public static void main(String[] args)
{
  Ball b=new Ball();
  b.bounce();
}
}</pre>
<p><strong>Explanation of Simple Example</strong></p>
<p>Lets understand this simple code&#8230;</p>
<ul>
<li>Here @ObjColor is an annotation applied on the class (or we can say attached to the class). It tells the tools , which will make use of it that the color of ball is Red that may be used by anybody. More important this extra information is attached to the class without extending , implementing or adding extra method or variable. this information can be used when required inside&#8230;like we have got value of color of ball&#8230;( String ballColor=Ball.class.getAnnotation(ObjColor.class).minecolor();//getting the value of minecolor element of ObjColor annotation)</li>
<li>As annotation is an special kind of interface. It must be imported from where it is defined. As we can see that this interface has @Target(ElementType.TYPE) it means this @ObjColor annotation can be applied to Class, interface (including annotation type), or enum declaration. and it has @Retention(RetentionPolicy.RUNTIME), which means this extra details attached is available upto runtime( Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively).</li>
</ul>
<h2>Replacing Deployment Descriptor with Annotations in EJB 3.0</h2>
<p>In container managed environment , components need many services (Like. Transaction, Security, Remotability etc.) which are provided by the container. For this purpose service configuration is required to be given to component which is used by container. Service configuration using <em>Java Metadata annotations</em> is easily the most important change in <strong>EJB 3.0</strong>. As we will see in other articles that annotations simplify the EJB programming model, eliminate the need for verbose(detailed) <em>Deployment Descriptor</em>. lets have a quick refresh about DD(Deployment Descriptor).</p>
<h3>What is Deployment Descriptor?</h3>
<p>A Deployment Descriptor is simply an XML based file that contains application confguration information. Every Deployment unit in Java EE can have a Deployment Descriptor that describes its contents and environment. Some example of deployment units are the Enterprise Archieve (EAR),Web Application Archieve (WAR), and the EJB module(ejb-jar). Deployment Descriptor file example as web.xml in Web Application Archieve and ejb-jar.xml in EJB module. One who has used EJB 2.0 , knows that how verbose the XML (ejb-jar.xml) descriptor was. <strong>EJB 3.0</strong> makes the use of DD optional. We can use metadata annotations instead of descriptor entries.</p>
<p><em><strong>Notes : </strong>Both Annotations and DD can be used togetherand Deployment Descriptor entries overrides configuration values hard coded in EJB components. The most obvious way of mixing and matching annotation and XML -Metadata is to use for deployment specific configurations while using annotations for everything else.</em></p>
<h3>Weakness of Annotations</h3>
<p>It isn&#8217;t always a good idea to mix and match configuration with source code such as annotations. This means that you would have to change source code each time you made a configuration change to something like a database connection resource or deployment descriptor environment entry.</p>
<h3>Common Annotations on EJB 3.0</h3>
<p>Here is a list of Metadata annotations introduced on Java EE. Although primarily geared towards <strong>EJB 3.0</strong>, thsese annotations apply to Java EE components such as Servlets and JSF managed beans as well as application clients. So we will see this list in relevence like usage of annotation and the Java EEcomponents which can use it. Annotations defined in the javax.annotation.* package are defined by the common <strong>Metadata Annotations API (JSR-250)</strong>.</p>
<ul>
<li><strong>javax.annotation.Resource</strong> :- Its usage is in Dependency injection of resources such as Data Source, JMS Objects etc. Components that can use this annotation are as : EJB, Web Components, application client.</li>
<li><strong>javax.annotation.PostConstruct</strong> :- Its usage is in declaring a method, a life cycle method. Components that can use this annotation are as : EJB, Web Components.</li>
<li><strong>javax.annotation.PreDestroy</strong> :- Its usage is in declaring a method , a life cycle method. Components that can use this annotation are as : EJB, Web Components.</li>
<li><strong>javax.annotation.security.RunAs</strong> :- Its usage is in security related coding. Components that can use this annotation are as : EJB, Web Components.</li>
<li><strong>javax.annotation.security.RolesAllowed</strong> :- Its usage is in security related coding. Components that can use this annotation are as : EJB.</li>
<li><strong>javax.annotation.security.PermitAll</strong> :- Its usage is in security related coding. Components that can use this annotation are as : EJB.</li>
<li><strong>javax.annotation.security.DenyAll</strong> :- Its usage is in security related coding. Components that can use this annotation are as : EJB.</li>
<li><strong>javax.annotation.security.DeclareRoles</strong> :- Its usage is in security related coding. Components that can use this annotation are as : EJB, Web Components.</li>
<li><strong>javax.ejb.EJB</strong> :- Its usage is in Dependency injection of Session Bean. Components that can use this annotation are as : EJB, Web Components, application client.</li>
<li><strong>javax.jws.WebServiceRef</strong> :- Its usage is in Dependency injection of Web Services. Components thact can use this annotation are as : EJB, Web Components, application client.</li>
<li><strong>javax.persistence.PersistenceContext</strong> :- Its usage is in Dependency injection of Container managed EntityManager. Components that can use this annotation are as : EJB, Web Components.</li>
<li><strong>javax.persistence.PersistenceUnit</strong> :- Its usage is in Dependency injection of EntityManagerFactory. Components that can use this annotation are as : EJB, Web Components.</li>
</ul>
<p>Here we have listed a few annotations. There are many other annotations on the J2ee plateform which we will be using it in all the future articles of <strong>EJB 3.0</strong>. Here the sole reason of listing some annotations and giving an example of annotation on<br />
<strong>Java 5.0</strong> plateform is to explain the functionality of annotations.</p>
<h2>Dependency Injection (DI) in EJB 3.0</h2>
<p><strong>Dependency Injection (DI)</strong> is another new feature of EJB 3.0. One who has worked in earlier version of EJB like EJB 2.0 knows that same repetition of code to lookup a resource or EJB using manual JNDI lookup.</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>To Solve the complxities surrounding manual JNDI lookups to inject a managed resource from container managed environment(like EJBs, DataSource,JMS Objects , EntityManager, EntityManagerFactory etc.). Almost every component uses another component or resource to implement functionality. The Primary goal of Dependency Injection is to make component interdependencies as loosely coupled as possible.</p>
<p>Resource can be accessed in your environment by two ways</p>
<ul>
<li>In Earlier versions of EJB resource ould be accessed by only JNDI lookup.</li>
<li>But now in <strong>EJB 3.0</strong> resource can be injected by JNDI lookup (as it was earlier) and by <strong> Dependency Injection as well</strong>.</li>
</ul>
<p>Dependency Injection is reversed of JNDI lookup. As you see in Manual JNDI lookup model, the bean explicitely retrieves the resource and components it needs. As a result, components and resource names are hard-coded in the bean. With DI , the container reads target bean configuration and then figures out what beans and resources the target bean needs and inject them into the bean at runtime. <strong>In the end with DI you write no lookup code and can easily change configuration to swap out beans and resources as needed. </strong></p>
<p><strong>Note:- </strong>In essence , Dependency Injection(DI) allows you to declare component dependencies and lets the container deal with the complexities of service or resource instantiation, initialization, sequencing and supplies the service or resource references to the clients as required.</p>
<p><strong>Here we will see one example and will notice the difference in manual JNDI look-up and Dependency Injection for an EJB compontent.</strong></p>
<p><strong>Example 1 </strong></p>
<pre class="brush: java; title: ; notranslate">//file1:- HelloStateless.java
package deepakPackage;
import javax.ejb.Remote;
@Remote
public interface HelloStateless {
 public void printMe(String msg);
}

.........
//file2:- HelloStatelessBean.java
package deepakPackage;
import javax.ejb.Stateless;
@Stateless
public class HelloStatelessBean  implements HelloStateless  {

 public void printMe(String msg)
 {
System.out.println(&quot;Hello Your message is : &quot;+msg);

 }

}
......
//file3: - MyServlet1.java Servlet Class MineServlet to use bean written
//above using Dependency Injection.....

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ejb.*;
import deepakPackage.*;
public class MyServlet1 extends HttpServlet {
      @EJB
      private HelloStateless hss;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
            response.setContentType(&quot;text/html;charset=UTF-8&quot;);
	        PrintWriter out = response.getWriter();
	        try {

	      out.println(&quot;Output of printMe() method is : &quot;+hss.printMe());
	      }

	        } finally {
	            out.close();
        }
    }

}
............................
//file4: -MyServlet2.java  Servlet Class MineServlet to use bean written above using JNDI lookup

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ejb.*;
import javax.naming.InitialContext;//extra import
import javax.naming.NamingException;//extra import
import deepakPackage.*;
public class MyServlet2 extends HttpServlet {

      private HelloStateless hss;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
            response.setContentType(&quot;text/html;charset=UTF-8&quot;);
	        PrintWriter out = response.getWriter();
	        try {
		InitialContext ic=new InitialContext();
		Object obj= (HelloStateless)ic.lookup(&quot;mineHelloStatelessBeanJNDIname&quot;);       		hss=(HelloStateless)Obj;
	      out.println(&quot;Output of printMe() method is : &quot;+hss.printMe());
	      }
catch(NamingException e)
{
System.out.println(&quot;Naming exception: &quot;+e.printStackTrace());
}

	        } finally {
	            out.close();
        }
    }

}</pre>
<p><strong>Code Explanation</strong></p>
<p>Here we can see that a stateless session bean has been written by using a POJO(Plain Old Java Object) HelloStateless annotated with @Remote from javax.ejb.Remote.class, which tells that this interface can be used as a remote interface for a bean to be accessed by remote clients remotely to access the methods which have been exposed in this interface as here printMe() so this printMe() method can be accessed by remote clients.</p>
<p>A POJO class HelloStatelessBean.java annotated with @Stateless from Javax.ejb.Stateless.class, which gives this POJO a status of an Enterprise Stateless bean. It says that this bean is stateless (in next article we will know what is stateless). This POJO class implements that business interface(HelloStateless.java) and implements methods exposed in that interface which is Remote. means this bean class can be used only by remote clients as it implements only remote interface. And methods can be accessed by only remote clients only.</p>
<p>Here we have given two servlets one is accessing the same bean using Dependency Injection and another using the same bean using JNDI lookup. So see the Difference in both the servlet.</p>
<ul>
<li>In First Servlet MyServlet1.java we have used Dependency Injection to inject a reference to the business interface of the bean whose method we want to access.One import :- import javax.ejb.EJB; and one statement :- @EJB HelloStateless hss; is required to get reference to the Business Interface of the bean.</li>
<li>In Second Servlet MyServlet2.java we have used manual JNDI lookup to get a reference to the business interface of the bean whose method we want to access. Here we need two imports :- import javax.naming.InitialContext; , import javax.naming.NamingException;and three statements :-<br />
InitialContext ic=new InitialContext(); ,<br />
Object obj= (HelloStateless)ic.lookup(&#8220;mineHelloStatelessBeanJNDIname&#8221;); , hss=(HelloStateless)Obj; ,<br />
is required to get reference to the Business Interface of the bean.</li>
</ul>
<p>Difference can be seen as how simple it is to inject a bean using Dependency Injection rather than using manual JNDI lookup.</p>
<h3>Conclusion</h3>
<p>Annotations which came in existence with JavaSE5, now have become default choice for configuaration of Metadata for resources.It support declarative programming and less code is required to fullfill the task and it eliminate the need for verbose and difficult to maintain Deployment Descriptor(exception is their as Default Listener we will see can be configured only with DD).</p>
<p>Dependency Injection as we have seen are dependent on annotations, provide an easy access to th resources binded in the JNDI. It provide an ease and a support for swap-out of resource as name of resources are not hard coded as in manual JNDI lookup. It lets the developer be happy and container resolve the complexities of resources to be injected in target component.</p>
<p>As both are the new features of EJB3.0 and provide ease in development and support declarative programming that improve the production.</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/2009/02/annotations-and-dependency-injection-in-ejb-3-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EJB 3.0 Entity Manager</title>
		<link>http://www.javabeat.net/2008/12/ejb-3-0-entity-manager/</link>
		<comments>http://www.javabeat.net/2008/12/ejb-3-0-entity-manager/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 16:04:04 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2246</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>Entities are classes that need to be persisted; their state is stored outside the application, typically in a relational database. Unlike session beans, entities do not have business logic other than validation. As well as storing such entities, we want to query, update, and delete them. The EJB 3.0 specification recognizes that many applications have the above persistence needs [...]</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>Entities are classes that need to be persisted; their state is stored outside the application, typically in a relational database. Unlike session beans, entities do not have business logic other than validation. As well as storing such entities, we want to query, update, and delete them.</p>
<p>The <b><i>EJB 3.0</i></b> specification recognizes that many applications have the above persistence needs without requiring the services (security, transactions) of an application server EJB container. Consequently the persistence aspects of <b><i>EJB 3.0</i></b> have been packaged as a separate specifi cation—the <b><i>Java Persistence API (JPA)</i></b>. <b><i>JPA</i></b> does not assume we have a container and can even be used in a Java SE (Standard Edition) application. As well as persistence, <b><i>JPA</i></b> deals with Object/Relational Mapping and Queries, these are covered in Chapters 4 and 5 respectively. Most of our examples assume that the persistence engine exists within an EJB 3 container such as GlassFish or JBoss. In Chapter 6 we shall show examples of persistence outside a container.</p>
<p>Successful standalone object-relational mapping products such as open source Hibernate and proprietary Oracle Toplink have implemented these persistence technologies for a number of years. Creators of Oracle Toplink and Hibernate have been infl uential in the development of the <b><i>JPA</i></b> specifi cation. So, readers who are familiar with either Hibernate or Toplink will recognize similarities between the <b><i>JPA </i></b>and those products. Furthermore, under the covers, the GlassFish application server implements the <b><i>JPA</i></b> using Toplink and the JBoss application server uses Hibernate. These are pluggable defaults however, so it is possible to implement the <b><i>JPA</i></b> in GlassFish using Hibernate for example.</p>
<p>The <b><i>JPA</i></b> can be regarded as a higher level of abstraction sitting on top of JDBC. Under the covers the persistence engine converts <b><i>JPA</i></b> statements into lower level JDBC statements.</p>
<h2 style="text-align: center;"><span style="text-decoration: underline;"><span style="color: #000080; text-decoration: underline;">EJB 3.0 Entities</span></span></h2>
<p>In <b><i>JPA</i></b>, any class or <i>POJO</i> (Plain Old Java Object) can be converted to an entity with very few modifications. The following listing shows an entity Customer.java with attributes id, which is unique for a Customer instance, and firstName and lastName.</p>
<pre class="brush: java; title: ; notranslate">package ejb30.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Customer implements java.io.Serializable {
private int id;
private String firstName;
private String lastName;
public Customer() {}
@Id
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFirstname() { return firstName; }
public void setFirstname(String firstName) {
this.firstName = firstName;
}
public String getLastname() { return lastName; }
public void setLastname(String lastName) {
this.lastName = lastName;
}
public String toString() {
return &amp;quot;[Customer Id =&amp;quot; + id + &amp;quot;,first name=&amp;quot; +
firstName + &amp;quot;,last name=&amp;quot; + lastName + &amp;quot;]&amp;quot;;
}
}
</pre>
<p>The class follows the usual JavaBean rules. The instance variables are non-public and are accessed by clients through appropriately named getter and setter accessor methods. Only a couple of <b><i>annotations</i></b> have been added to distinguish this entity from a <i>POJO</i>. <b><i>Annotations</i></b> specify entity metadata. They are not an intrinsic part of an entity but describe how an entity is persisted or, as we shall see in Chapter 4, how an entity is related to other entities. The @Entity annotation indicates to the persistence engine that the annotated class, in this case Customer, is an entity. The annotation is placed immediately before the class defi nition and is an example<br />
of a class level annotation. We can also have property-based and fi eld-based <b><i>annotations</i></b>, as we shall see.</p>
<p>The @Id annotation specifi es the primary key of the entity. The id attribute is a primary key candidate. Note that we have placed the annotation immediately before the corresponding getter method, getId(). This is an example of a property-based annotation. A property-based annotation must be placed immediately before the corresponding getter method, and not the setter method. Where property-based <b><i>annotations</i></b> are used, the persistence engine uses the getter and setter methods to access and set the entity state.</p>
<p>An alternative to property-based <b><i>annotations</i></b> are fi eld-based <b><i>annotations</i></b>. We show an example of these later in this chapter. Note that all <b><i>annotations</i></b> within an entity, other than class level <b><i>annotations</i></b>, must be all property-based or all fi eld-based.<br />
The final requirement for an entity is the presence of a no-arg constructor. Our Customer entity also implements the java.io.Serializable interface. This is not essential, but good practice because the Customer entity has the potential of becoming a detached entity. Detached entities must implement the Serializable interface. We will discuss detached entities in Chapter 6.</p>
<p>At this point we remind the reader that, as throughout EJB 3.0, <i>XML</i> deployment descriptors are an alternative to entity metadata <b><i>annotations</i></b>.</p>
<h2>Comparison with EJB 2.x Entity Beans</h2>
<p>An EJB 3.0 entity is a POJO and not a component, so it is referred to as an entity and not an entity bean. In <b><i>EJB 2.x</i></b> the corresponding construct is an entity bean component with the same artifacts as session beans, namely an <i>XML</i> deployment descriptor fi le, a remote or local interface, a home or localhome interface, and the bean class itself. The remote or local interface contains getter and setter method defi nitions. The home or local interface contains defi nitions for the create() and findByPrimaryKey() methods and optionally other fi nder method defi nitions. As with session beans, the entity bean class contains callback methods such as ejbCreate(), ejbLoad(), ejbStore(), ejbRemove(), ejbActivate(), ejbPassivate(), and setEntityContext().</p>
<p>The <b><i>EJB 3.0</i></b> entity, being a POJO, can run outside a container. Its clients are always local to the JVM. The <b><i>EJB 2.x</i></b> entity bean is a distributed object that needs a container to run, but can have clients from outside its JVM. Consequently EJB 3 entities are more reusable and easier to test than <b><i>EJB 2.x</i></b> entity beans.</p>
<p>In <b><i>EJB 2.x</i></b> we need to decide whether the persistence aspects of an entity bean are handled by the container (Container Managed Persistence or CMP) or by the application (Bean Managed Persistence or BMP).</p>
<p>In the case of CMP, the entity bean is defi ned as an abstract class with abstract getter and setter method defi nitions. At deployment the container creates a concrete implementation of this abstract entity bean class.</p>
<p>In the case of BMP, the entity bean is defi ned as a class. The getter and setter methods need to be coded. In addition the ejbCreate(), ejbLoad(), ejbStore(),ejbFindByPrimaryKey(), and any other fi nder methods need to be coded using JDBC.</p>
<h2>Mapping an Entity to a Database Table</h2>
<p>We can map entities onto just about any relational database. GlassFish includes an embedded Derby relational database. If we want GlassFish to access another relational database, Oracle say, then we need to use the GlassFish admin console to set up an Oracle data source. We also need to refer to this Oracle data source in the persistence.xml fi le. We will describe the persistence.xml fi le later in this chapter. These steps are not required if we use the GlassFish default Derby data source. All the examples in this book will use the Derby database.</p>
<p>EJB 3 makes heavy use of defaulting for describing entity metadata. In this section we describe a few of these defaults.</p>
<p>First, by default, the persistence engine maps the entity name to a relational table name. So in our example the table name is CUSTOMER. If we want to map the Customer entity to another table we will need to use the @Table annotation as we shall see later in this chapter.</p>
<p>By default, property or fi elds names are mapped to a column name. So ID, FIRSTNAME, and LASTNAME are the column names corresponding to the id, firstname, and lastname entity attributes. If we want to change this default behavior we will need to use the @Column annotation as we shall see later in this chapter.</p>
<p>JDBC rules are used for mapping Java primitives to relational datatypes. So a String will be mapped to VARCHAR for a Derby database and VARCHAR2 for an Oracle database. An int will be mapped to INTEGER for a Derby database and NUMBER for an<br />
Oracle database.</p>
<p>The size of a column mapped from a String defaults to 255, for example VARCHAR(255) for Derby or VARCHAR2(255) for Oracle. If we want to change this column size then we need to use the length element of the @Column annotation as we shall see later in this chapter.</p>
<p>Most persistence engines, including the GlassFish default persistence engine, Toplink, have a schema generation option, although this is not required by the <b><i>JPA </i></b>specifi cation. In the case of GlassFish, if a fl ag is set when the application is deployed to the container, then the container will create the mapped table in the database. Otherwise the table is assumed to exist in the database.</p>
<h2>What <b><i>EJB 3.0</i></b> Developer Guide Covers</h2>
<ul>
<li>Chapter 1 Introduction to EJB 3—A general overview of the Java EE architecture including EJB container services, the <b><i>JPA</i></b> persistence engine, and initial installation of the GlassFish application server.</li>
<li>Chapter 2 Session Beans—Creation of a session bean and its client and examples of running it from the application client container. Exploring the program directory structure. Packaging and deploying a session bean. A look at the stateless and stateful session beans lifecycle.</li>
<li>Chapter 3 Entities—Exploring <b><i>EJB 3.0</i></b> entities. How to package and deploy entities and map an entity to a database table. Metadata defaults and how to override them. Generating primary keys.</li>
<li>Chapter 4 Object/Relational Mapping—One-to-one, one-to-many and many-to-many associations. Default object/relational mapping values and how to override them. Object/relational inheritance mapping and additional <b><i>annotations</i></b>.</li>
<li>Chapter 5 <b>JPQL (Java Persistence Query Language)</b>—Looking at different groups of queries including aggregate functions, queries with relationships, subqueries, queries with parameters and named queries. <b>JPQL</b> joins and functions are also explained.</li>
<li>Chapter 6 Entity Manager—Looks in detail at the entity manager. Covers both the EJB 3 container-managed and application-managed entity managers.</li>
<li>Chapter 7 Transactions—ACID properties and isolation levels. Container-managed transactions. Bean-managed transactions.</li>
<li>Chapter 8 Messaging—Looks at the <b>JMS (Java Messaging Service) API</b>. Examples of queue producer and queue consumers. Topic producer and consumers. Message driven beans: their activation configuration properties, lifecycles and transactions.</li>
<li>Chapter 9 EJB Timer Service—Examples of single and interval events. Timer interface methods. Timers and transactions.</li>
<li>Chapter 10 Interceptors—Covers interceptor methods, classes and interceptor communication as well as default interceptors.</li>
<li>Chapter 11 Implementing <b><i>EJB 3.0</i></b> Web Services—An overview of web service concepts and the web service definition language (WSDL). Creating and deploying a Java application as a web service. Creating and deploying an EJB session bean as a web service. Creating a web service client.</li>
<li>Chapter 12 <b><i>EJB 3.0</i></b> Security—A look at security, GlassFish authentication, declarative and programmatic EJB authorization and Web Tier authentication and authorization.</li>
<li>The Appendix shows <b><i>EJB 3.0</i></b> <b><i>annotations</i></b> described in this book with their corresponding packages.</li>
</ul>
<h2>Introducing the EntityManager</h2>
<p>We will use a remote stateless session bean for business operations on the Customer entity. We will call our session bean interface BankService. In later chapters, we will add more entities and business operations that are typically used by a banking application. At this stage our banking application deals with one entity—Customer, and business methods addCustomer() and findCustomer(), which respectively add a customer to the database and retrieve a customer entity given the customers identifier. The interface listing follows:</p>
<pre class="brush: java; title: ; notranslate">package ejb30.session;
import javax.ejb.Remote;
import ejb30.entity.Customer;
@Remote
public interface BankService {
void addCustomer(int custId, String firstName,
String lastName);
Customer findCustomer(int custId);
}
</pre>
<p>The code below shows the session bean implementation, BankServiceBean:</p>
<pre class="brush: java; title: ; notranslate">package ejb30.session;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import ejb30.entity.Customer;
import javax.persistence.PersistenceContext;
@Stateless
public class BankServiceBean implements BankService {
@PersistenceContext(unitName=&amp;quot;BankService&amp;quot;)
private EntityManager em;
public Customer findCustomer(int custId) {
return ((Customer)
em.find(Customer.class, custId));
}
public void addCustomer(int custId, String firstName,
String lastName) {
Customer cust = new Customer();
cust.setId(custId);
cust.setFirstname(firstName);
cust.setLastname(lastName);
em.persist(cust);
}
}
</pre>
<p>The EntityManager is a service provided by the persistence engine which provides methods for persisting, fi nding, querying, removing, and updating entities. The set of managed entity instances is known as a persistence context. It is important to stress that a persistence context is associated with a managed set of entity instances or objects. If we have, say, 10 clients accessing the bean, we will have 10 persistence contexts. Associated with an EntityManager is a persistence unit which specifi es configuration information. The statement:</p>
<pre class="brush: java; title: ; notranslate">@PersistenceContext(unitName=&amp;quot;BankService&amp;quot;)
private EntityManager em;
</pre>
<p>defi nes an EntityManager instance em with an associated persistence context and a persistence unit named BankService. The actual persistence unit confi guration is specifi ed in a persistence.xml fi le which we shall see shortly.</p>
<p>Actually, behind the scenes, the @PersistenceContext annotation causes the container to:</p>
<ul>
<li>Use the EntityManagerFactory to create an instance of the EntityManager</li>
<li>Bind the EntityManager instance to the BankService persistence unit</li>
<li>Inject the EntityManager instance into the em field.</li>
</ul>
<p>Now let&#8217;s take a look at the addCustomer() method. First, the statement</p>
<pre class="brush: java; title: ; notranslate">Customer cust = new Customer();
</pre>
<p>creates, as expected, an instance of the Customer entity. However, at this stage the entity instance is not managed. The instance is not yet associated with a persistence context. Managed entity instances are also referred to as attached instances and unmanaged instances as detached instances.</p>
<p>The next few statements invoke the Customer setter methods in the usual way. The statement:</p>
<pre class="brush: java; title: ; notranslate">em.persist(cust);
</pre>
<p>invokes the EntityManager.persist() method. At this stage the entity instance is not necessarily written immediately to the database. Rather, the entity instance becomes managed or attached and associated with a persistence context. The EntityManager manages the synchronization of a persistence context with the database. There may be more setter methods in our method after the persist()<br />
statement. The EntityManager is unlikely to update, or fl ush, the database after each setter as database write operations are expensive in terms of performance. More likely the entity state would be kept in a cache and fl ushed to the database at the end of the current transaction. The latest point at which the EntityManager will fl ush to the database is when the transaction commits, although the EntityManager may chose to fl ush sooner.</p>
<p>By default, a transaction starts when a method is invoked, and is committed on leaving a method. We will discuss transactions further in Chapter 7.</p>
<p>Now let&#8217;s look at the findCustomer() method. The statement:</p>
<pre class="brush: java; title: ; notranslate">return ((Customer) em.find(Customer.class, custId));
</pre>
<p>invokes the EntityManager.find() method. This method retrieves an entity by its primary key. The parameters of find() are the entity class and a primary key, which is an Object type, which uniquely identifi es the entity. In our example we use the variable custId as the primary key (the autoboxing feature of Java SE 5 converts the supplied int type to an Object type).</p>
<p>The EntityManager service also provides a query language, JPQL, which we will cover in Chapter 5. Furthermore the EntityManager provides entity management methods, such as merging detached entities. At this stage the reader might think that entities should always be in an attached (managed) state, however we shall see examples in Chapter 6 where entities do exist in a detached state.</p>
<p>The following listing is an example of how a client might invoke the BankServicemethods to create and then find an entity.</p>
<pre class="brush: java; title: ; notranslate">package ejb30.client;
import javax.naming.Context;
import javax.naming.InitialContext;
import ejb30.session.*;
import ejb30.entity.Customer;
import javax.ejb.EJB;
public class BankClient {
@EJB
private static BankService bank;
public static void main(String[] args) {
try {
int custId = 0;
String firstName = null;
String lastName = null;
try {
custId = Integer.parseInt(args[0]);
firstName = args[1];
lastName = args[2];
} catch (Exception e) {
System.err.println(
&amp;quot;Invalid arguments entered, try again&amp;quot;);
System.exit(0);
}
// add customer to database
bank.addCustomer(custId, firstName, lastName);
Customer cust = bank.findCustomer(custId);
System.out.println(cust);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
}
</pre>
<p>The code is fairly straightforward. The variables custId, firstName, and lastName are initialized to parameters supplied to the main method when it is invoked. The client uses the BankService.addCustomer() method to create and add a Customer entity to the database. The BankService.findCustomer() method is then invoked to retrieve the entity just created.</p>
<p>We now return to the persistence unit which we referred to in the @PersistenceContext annotation that we used in the BankService session bean. The actual confi guration is specifi ed in an XML file, persistence.xml, which is shown below:</p>
<pre class="brush: java; title: ; notranslate">&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot;?&amp;gt;
&amp;lt;persistence xmlns=&amp;quot;http://java.sun.com/xml/ns/persistence&amp;quot;
version=&amp;quot;1.0&amp;quot;&amp;gt;
&amp;lt;persistence-unit name=&amp;quot;BankService&amp;quot;/&amp;gt;
&amp;lt;/persistence&amp;gt;
</pre>
<p>Again we make heavy use of defaults here. A persistence.xml fi le is required whenever an application makes use of EntityManager services, even if we rely entirely on defaults. In our case we have just used the name element to defi ne the BankService persistence unit. Note the name must match the unitName used earlier in the @PersistenceContext annotation. There are a number of persistence unit elements, in particular regarding transactions and data sources. We will return to these elements later in the book.</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>
<h2>Packaging and Deploying Entities</h2>
<p>As we have introduced a number of new source code artifacts that were not present in the previous chapter on session beans, the packaging process will be a little different. First we look at the program directory structure for our sample application.</p>
<h2>Building the Application</h2>
<p>B ecause we are persisting entities from an EJB container we need to place the persistence.xml fi le in the META-INF directory within the EJB module, BankService.jar. The package-ejb target in the Ant build fi le does this:</p>
<pre class="brush: java; title: ; notranslate">&amp;lt;target name=&amp;quot;package-ejb&amp;quot; depends=&amp;quot;compile&amp;quot;&amp;gt;
&amp;lt;jar jarfile=&amp;quot;${build.dir}/BankService.jar&amp;quot;&amp;gt;
&amp;lt;fileset dir=&amp;quot;${build.dir}&amp;quot;&amp;gt;
&amp;lt;include name=&amp;quot;ejb30/session/**&amp;quot; /&amp;gt;
&amp;lt;include name=&amp;quot;ejb30/entity/**&amp;quot; /&amp;gt;
&amp;lt;/fileset&amp;gt;
&amp;lt;metainf dir=&amp;quot;${config.dir}&amp;quot;&amp;gt;
&amp;lt;include name=&amp;quot;persistence.xml&amp;quot; /&amp;gt;
&amp;lt;/metainf&amp;gt;
&amp;lt;/jar&amp;gt;
&amp;lt;/target&amp;gt;
We can use the jar –tvf command to examine the contents of the JAR fi le:
C:\EJB3Chapter03\glassfish\lab1\build&amp;gt;jar –tvf BankService.jar
...META-INF/
...META-INF/MANIFEST.MF
...ejb30/
...ejb30/entity/
...ejb30/session/
...ejb30/entity/Customer.class
...ejb30/session/BankService.class
...ejb30/session/BankServiceBean.class
...META-INF/persistence.xml
</pre>
<p>This is only one of a number of ways to package the persistence unit. Entities can be persisted not only from an EJB container but also from a web container or from a Java SE application running outside the container. We shall see an example of Java SE persistence in Chapter 6. Consequently the persistence unit (entity classes together with the persistence.xml fi le) can be placed in WEB-INF/classes<br />
directory of a WAR fi le or in a Java SE application client jar file.</p>
<p>Alternatively we can package a persistence unit into can then be added to the WEB-INF/lib directory file or in the library directory of an EAR fi le. Adding module limits its scope to that module. If we place is visible to all modules within the application.</p>
<p>In our example we want the database tables to be created at deploy time, and dropped when we undeploy an application from the container. We modify the deploy target in our Ant build fi le, adding a createtables=true clause:</p>
<pre class="brush: java; title: ; notranslate">&amp;lt;target name=&amp;quot;deploy&amp;quot;&amp;gt;
&amp;lt;exec executable=&amp;quot;${glassfish.home}/bin/asadmin&amp;quot;
failonerror=&amp;quot;true&amp;quot;
vmlauncher=&amp;quot;false&amp;quot;&amp;gt;
&amp;lt;arg line=&amp;quot;deploy --user admin --passwordfile
adminpassword --createtables=true
${build.dir}/BankService.ear&amp;quot;/&amp;gt;
&amp;lt;/exec&amp;gt;
&amp;lt;/target&amp;gt;
Similarly we add a droptables=true clause for the undeploy target.
&amp;lt;target name=&amp;quot;undeploy&amp;quot;&amp;gt;
&amp;lt;exec executable=&amp;quot;${glassfish.home}/bin/asadmin&amp;quot;
failonerror=&amp;quot;true&amp;quot;
vmlauncher=&amp;quot;false&amp;quot;&amp;gt;
&amp;lt;arg line=&amp;quot;undeploy --user admin --passwordfile
adminpassword --droptables=true BankService&amp;quot;/&amp;gt;
&amp;lt;/exec&amp;gt;
&amp;lt;/target&amp;gt;
</pre>
<p>Note that before we can deploy BankService within GlassFish, we need to start up the embedded Derby database. We do this from the command-line with the asadmin utility: C:\&gt; asadmin start-database</p>
<h2>Field-Based Annotations</h2>
<p>Recall we used a property-based annotation for the primary key @Id in the Customer entity. This results in the persistence engine using getter and setter methods to access and set the entity state. In this section we will modify the Customer entity to use fi eld-based, rather than property-based annotations. The following listing demonstrates this:</p>
<pre class="brush: java; title: ; notranslate">@Entity
public class Customer implements java.io.Serializable {
@Id
private int id;
private String firstName;
@Basic
private String lastName;
public Customer() {};
public Customer(int id, String firstName,
String lastName){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFirstname() { return firstName; }
public void setFirstname(String firstName) {
this.firstName = firstName;
}
public String toString() {
return &amp;quot;[Customer Id =&amp;quot; + id + &amp;quot;,first name=&amp;quot; +
firstName + &amp;quot;,last name=&amp;quot; + lastName + &amp;quot;]&amp;quot;;
}
}
</pre>
<p>Note that we have placed the primary key @Id annotation immediately before the field declaration. If we use a fi eld-based annotation then all other annotations, other than class level annotations such as @Entity, must also be fi eld-based annotations. In the case of fi eld-based annotations the persistence engine will use refl ection to access and set the entity state. Getter and setter methods may be present in the entity but they are ignored by the persistence engine. To demonstrate this point we have removed the getLastName() and setLastName() methods from the Customer entity.</p>
<p>We have seen that attributes other than the primary key are mapped to a database by default. We call these mappings basic mappings. A basic mapping is used where the attribute is a Java primitive type or any Serializable type such as a String. We can<br />
explicitly fl ag these mappings using the @Basic annotation. We have done this for the lastName field.</p>
<h2>Generating Primary Keys</h2>
<p>Upto now we have relied on the application to set an entity&#8217;s primary key by supplying a primary key identifi er as a parameter. However, we may want to relieve the application of this responsibility and use automatically generated keys. <b><i>JPA </i></b>provides the Table, Sequence, Auto, and Identity strategies for generating primary keys.</p>
<h2>Table Strategy</h2>
<p>With this strategy the persistence engine uses a relational database table from which the keys are generated. This strategy has the advantage of portability; we can use it with any relational database. Here is an example of how we would specify a table generation strategy for the id attribute of the Customer entity:</p>
<pre class="brush: java; title: ; notranslate">@TableGenerator(name=&amp;quot;CUST_SEQ&amp;quot;,
table=&amp;quot;SEQUENCE_TABLE&amp;quot;,
pkColumnName=&amp;quot;SEQUENCE_NAME&amp;quot;,
valueColumnName=&amp;quot;SEQUENCE_COUNT&amp;quot;)
@Id
@GeneratedValue(strategy=GenerationType.TABLE,
generator=&amp;quot;CUST_SEQ&amp;quot;)
public int getId() { return id; }
</pre>
<p>First we use the @TableGenerator annotation to specify the table used for key generation. This annotation can be placed on the primary key attribute, as we have done here, or on the entity class.</p>
<p>The name element in our example CUST_SEQ, identifi es the generator. The table element is the name of the table that stores the generated values. In our case we have chosen SEQUENCE_TABLE as the table name. There is a default table element, but this is dependent on the persistence engine being used. In the case of GlassFish, this table name is SEQUENCE. The pkColumnName element is the name of the primary key column in the sequence table. We have chosen SEQUENCE_NAME as the column name. Again the default is persistence engine dependent. In the case of GlassFish this value is SEQ_NAME. The valueColumnName element is the name of the column that stores the last key value generated. The default is persistence engine dependent. In the case of GlassFish this value is SEQ_COUNT.</p>
<p>One element of @TableGenerator for which we assumed the default is pkColumnValue. This is the String value that is entered in the pkColumnName column. The default is persistence engine dependent. In the case of GlassFish, this value is set to the name element of @TableGenerator. In our example this is CUST_SEQ. So SEQUENCE_TABLE will initially have the following row present:</p>
<pre class="brush: java; title: ; notranslate">SQL&amp;gt; SELECT * FROM SEQUENCE_TABLE;
SEQUENCE_NAME SEQUENCE_COUNT
------------- --------------
CUST_SEQ 0
</pre>
<p>If we want to store several sequences in the same sequence table, for example a separate sequence for each entity, then we need to manually specify the pkColumnValue element. The following statement sets the pkColumnValue to</p>
<pre class="brush: java; title: ; notranslate">CUSTOMER_SEQ:
@TableGenerator(name=&amp;quot;CUST_SEQ&amp;quot;,
table=&amp;quot;SEQUENCE_TABLE&amp;quot;,
pkColumnName=&amp;quot;SEQUENCE_NAME&amp;quot;,
valueColumnName=&amp;quot;SEQUENCE_COUNT&amp;quot;,
pkColumnValue=&amp;quot;CUSTOMER_SEQ&amp;quot;)
</pre>
<p>We should mention two other @TableGenerator elements: initialValue and allocationSize. initialValue is the initial value assigned to the primary key sequence. The default value is 0. The sequence is incremented by a value of 1. The allocationSize is the cache size into which the persistence engine reads from the sequence table. The default value is 50.</p>
<p>The @GeneratedValue annotation specifi es the key generation strategy with the strategy element. In our case we have chosen the TABLE strategy. The default strategy is AUTO which we describe later in this chapter. The generator element provides the name of the primary key generator. In our case this is CUST_SEQ and must match the name element of the @TableGenerator annotation. The<br />
@GeneratedValue annotation is a fi eld-based or property-based annotation, so must be present immediately before the primary key fi eld or getter method.</p>
<h2>Sequence Strategy</h2>
<p>Some databases, such as Oracle, have a built-in mechanism called sequences for generating keys. To invoke such a sequence we need to use the @SequenceGenerator annotation. For example:</p>
<pre class="brush: java; title: ; notranslate">@SequenceGenerator(name=&amp;quot;CUST_SEQ&amp;quot;,
sequenceName=&amp;quot;CUSTOMER_SEQUENCE&amp;quot;)</pre>
<p>As with the @TableGenerator annotation, the name element identifi es the generator. The sequenceName element identifi es the database sequence object. initialValue is the initial value assigned to the primary key sequence. The default differs from the @TableGenerator equivalent, and is equal to 1. The allocationSize is the cache size into which the persistence engine reads from the sequence. The default value is 50.</p>
<p>The @SequenceGenerator annotation can be placed on the primary key attribute or on the entity class.</p>
<p>As with Table generated sequences, we use the @GeneratedValue annotation to specify the generation strategy. For example,</p>
<pre class="brush: java; title: ; notranslate">@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,
generator=&amp;quot;CUST_SEQ&amp;quot;)
</pre>
<p>This time we have specifi ed the SEQUENCE strategy. The name of the primary key generator is CUST_SEQ, and this must match the name element of the @SequenceGenerator annotation. Remember the @GeneratedValue annotation is a fi eld-based or property-based annotation, so it must be present immediately before the primary key fi eld or getter method.</p>
<h2>Identity Strategy</h2>
<p>Some databases, such as Microsoft SQL Server, use an identity column for generating keys. To use this we specify the IDENTITY strategy in the @GeneratedValue annotation:</p>
<pre class="brush: java; title: ; notranslate">@GeneratedValue(strategy=GenerationType.IDENTITY)
</pre>
<p>Note that there is no generator element that we have for the Table and Sequence strategies.</p>
<h2>Auto Strategy</h2>
<p>The final strategy is the AUTO strategy. With this strategy the persistence engine selects the strategy. In the case of GlassFish the TABLE strategy is selected. We can specify an AUTO strategy either explicitly:</p>
<pre class="brush: java; title: ; notranslate">@GeneratedValue(strategy=GenerationType.AUTO)
or implicitly:
@GeneratedValue
as the default strategy is AUTO.
</pre>
<h2>Overriding Metadata Defaults</h2>
<p>In this section we return to the Customer entity and override some of the default mapping options.</p>
<p>First we want to use the CLIENT table with columns CUSTOMER_ID, FIRST_NAME and LAST_NAME to store Customer entities. The primary key is CUSTOMER_ID. The table defi nition is:</p>
<pre>,code&gt;
CLIENT
CUSTOMER_ID NUMBER(38) PRIMARY KEY
FIRST_NAME VARCHAR(30) NOT NULL
LAST_NAME VARCHAR(30) NOT NULL</pre>
<p>The modified listing for Customer.java is shown below:</p>
<pre class="brush: java; title: ; notranslate">@Entity
@Table(name = &amp;quot;CLIENT&amp;quot;)
public class Customer implements java.io.Serializable {
private int id;
private String firstName;
private String lastName;
public Customer() {};
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = &amp;quot;CUSTOMER_ID&amp;quot;)
public int getId() { return id; }
public void setId(int id) { this.id = id; }
@Column(name = &amp;quot;FIRST_NAME&amp;quot;)
public String getFirstname() { return firstName; }
public void setFirstname(String firstName) {
this.firstName = firstName;
}
@Column(name = &amp;quot;LAST_NAME&amp;quot;)
public String getLastname() { return lastName; }
public void setLastname(String lastName) {
this.lastName = lastName;
}
public String toString() {
return &amp;quot;[Customer Id =&amp;quot; + id + &amp;quot;,first name=&amp;quot; +
firstName + &amp;quot;,last name=&amp;quot; + lastName + &amp;quot;]&amp;quot;;
}
}
</pre>
<p>Note we have used the @Table annotation to specify the table name as CLIENT. The default table name is the entity name, CUSTOMER in our example. The catalog element specifi es the database catalog where the table is located. Many database systems, Derby included, do not support the concept of a catalog. So in our example we can leave this element out. The schema element specifi es the database schema where the table is located. The default is persistence provider specifi c, in the case of the GlassFish APP is the default schema for the embedded Derby database. Again, in our example, we rely on the default.</p>
<p>We have explicitly specifi ed an AUTO primary key generation strategy:</p>
<pre class="brush: java; title: ; notranslate">@Id
@GeneratedValue(strategy=GenerationType.AUTO)
</pre>
<p>Recall that GlassFish selects the TABLE strategy in this case.</p>
<p>Recall that by default column names are set to attribute names. To override this we<br />
use the @Column annotation. For example,</p>
<pre class="brush: java; title: ; notranslate">
@Column(name = &amp;quot;CUSTOMER_ID&amp;quot;)
public int getId() { return id; }
</pre>
<p>will map the id attribute to the CUSTOMER_ID column. In a similar fashion we map<br />
the firstName and lastName attributes to the FIRST_NAME and LAST_NAME<br />
columns respectively.</p>
<h2>Summary</h2>
<p>Entities are classes that need to be persisted, usually in a relational database. The persistence aspects of EJB 3 have been packaged as a separate specifi cation, the Java Persistence API (<b><i>JPA</i></b>), so that applications that do not need EJB container services can still persist their entities to a relational database. Persistence services are handled by a persistence engine. In this chapter we make use of the Toplink persistence engine that comes bundled with the GlassFish application server.</p>
<p>Any Java class, or POJO, can be converted to an entity using metadata annotations. We described by means of an example the default rules for mapping an entity to a relational database table.</p>
<p><em id="__mceDel">We introduced the EntityManager service, which provides methods for persisting, fi nding, querying, removing and updating entities. We saw examples of the EntityManager.persist() and EntityManager.find() methods. We introduced the concept of a persistence context, which is the set of managed entity instances. We looked at Ant scripts for packaging and deploying an application which uses entities.</em></p>
<p><em id="__mceDel"><em id="__mceDel"><em id="__mceDel"><em id="__mceDel"><em id="__mceDel">We examined strategies for generating primary keys. Finally we looked at examples of overriding default rules for mapping entities to relational tables.</em></em></em></em></em></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/12/ejb-3-0-entity-manager/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EJB 3.0 and WebServices</title>
		<link>http://www.javabeat.net/2008/07/ejb-3-webservices/</link>
		<comments>http://www.javabeat.net/2008/07/ejb-3-webservices/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 00:43:04 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6856</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 discusses how an enterprise bean can act as a Web-Service component. Since Web-Services itself is a vast technology, the first part of the article discusses more about Web-Services. Specifically, the first part of the article discusses what Web-Services are, its unique features among other related technologies, its architecture, and the various base components [...]</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 discusses how an enterprise bean can act as a Web-Service component. Since Web-Services itself is a vast technology, the first part of the article discusses more about Web-Services. Specifically, the first part of the article discusses what Web-Services are, its unique features among other related technologies, its architecture, and the various base components upon which Web- Services are built. The second part of the article describes the JSR-181 which is the “Web-Services Meta-data for the Java Platform” and how enterprise beans can make use of the API’s available under this JSR to expose themselves as Web-Services components.</p>
<h2>Web Services</h2>
<h4>Introduction</h4>
<p>Normally a Service represents any kind of feature or some piece of functionality that a specific kind of client can be benefited from. Say for a printer service, the clients are either the applications or the programs using the printers or users. Consumers of an ATM service are Bank Customers, like-wise the list of real-world services goes on.</p>
<p>Like these kinds of service, a Web-Service is a kind of remote service that is available in the web and it can be accessed through some standard protocols. A Web-Service can be imagined as a program that is running in a remote machine, usually guarded by a server, so that it can be made accessible by remote clients. How Web-Services are very different from the existing technologies is that, Web-Services have some unique features that are very uncommon to other existing technologies. The clients for these Web-Services can be any one, it can be a user or HTML browser, or even another Web-Service.</p>
<h2>Features of Web Services</h2>
<p>Following are the unique features of a Web-Service based application.</p>
<ul>
<li>Language Independent</li>
<li>Operating System Independent</li>
</ul>
<h2>Language Independent</h2>
<p>Let us assume that a Web-Service is running in a remote machine. Suppose an application (can be a Web-Service also) want to gain the functionality of the Web-Service by accessing it. It is not that both the Web-Service and the client application must be built in the same language or technology. They can be different. From this, we can infer that a Web-Service can be built in Java, running in some remote machine and the client of the Web-Service can be a legacy C++ application or a DotNET application.</p>
<h2>Communication between Web-Service and heterogeneous clients</h2>
<p>From the above diagram, we can see that 3 different applications (built on 3 different technologies) are accessing the same Web-Service.</p>
<h2>Operating System Independent</h2>
<p>Web-Services are independent of operating systems. This implies that the Web-Service and its consumer can be running in different operating systems. It means that an application running in Unix operating system can access a Web-Service that is running in Windows OS. This is possible, because of the fact that, Web-Services have their specifications defined by W3C and vendors who are providing implementations for the various Web-Services standards are bound to follow the specifications.</p>
<p>[W3C, which stands for World Wide Web Consortium, is a group of companies for proposing and defining some standards for World Wide Web (W3). A whole bunch of Internet standards have been given by W3C till now. Major standards include HTML, XHTML, XML, SOAP, and WSDL…]</p>
<h2>Comparison with Other Technologies</h2>
<p>If we have a broader look over Web-Services, it is nothing but a distributed computing enabling integration between applications. So many distributing computing standards are there till date and each of them have their own set of limitations. Some of the popular distributing computing technologies include COM-DCOM from Microsoft, Java’s RMI and <a href="http://www.javabeat.net/articles/print.php?article_id=80#"><span style="color: blue;">EJB</span></a> and Object Managements’ Group CORBA. Each of the above-mentioned technologies seriously suffered from issues like portability, platform-dependency, etc.,</p>
<p>Considering the effort taken by Microsoft to give a common solution to Distributed computing is that both COM (Component Object Model) and DCOM (Distributed Component Object Model) technologies allowed Component based software model development and the components can only be written in a language like VB, VC++ or any Microsoft’s compliant language. Therefore, components written in VB and VC++ can communicate with each other and this doesn’t seem to promote language independency. Another issue is that these COM and DCOM technologies are available only in Operating systems like Windows 98, XP and 2000.</p>
<p>Sun’s Remote Method Invocation, through the support of Java Remote Method Protocol (JRMP) , though is operating system independent (as <a href="http://www.javabeat.net/articles/print.php?article_id=80#"><span style="color: blue;">Java code</span></a> can be written only once and can be run anywhere as long as a JVM is installed in the target operating system), lacked the same issue of language independency. Both RMI enabled servers and clients should only be written in Java. Outside languages are prohibited to take the advantage of this distributed computing. Though, EJB has support to integrate well with other technologies like DotNet, it hasn’t become very popular, as providing integration of a <a href="http://www.javabeat.net/articles/print.php?article_id=80#"><span style="color: blue;">J2EE</span></a> Component with other technologies, for sure, will lose the efficiency of portability of the applications in other platforms.</p>
<p>In comparison with the other two technologies, CORBA almost eliminated all the serious issues by providing a language independent and a platform independent framework. It means that in a distributed application, a C++ Server can talk to a Java Client and vice versa. Though this looks good from the outside view, there are other issues like maintaining a heavy middle-ware between the client and the server called Object Adapter and Object Broker, which does the job of locating and loading servers, creating server objects on behalf of clients etc., which made it to prevent from being a successful technology.</p>
<h2>Web Services Architecture</h2>
<p>A Web Service is not a single technology but it is a combination of several other technologies like</p>
<ul>
<li>SOAP</li>
<li>WSDL</li>
<li>UDDI</li>
</ul>
<p>Following sections cover these technologies in greater depth.</p>
<p><span style="text-decoration: underline;"><b>SOAP</b></span></p>
<p>For establishing communication between heterogeneous systems for exchange of data, we have to adhere to some set of standards in the form of protocols. Distributed computing technologies like<b>DCOM, CORBA, and RMI</b> etc. have their own proprietary protocols. For example, <b>CORBA </b>uses<b> IIOP (Internet Inter-ORB Protocol) </b>as the standard protocol for communication, <b>DCOM</b> uses <b>ORPC</b>(<b>Object Remote Procedure Call</b>) and <b>Java’s RMI</b> used <b>JRMP</b> (<b>Java Remote Method Protocol</b>). Similarly, Web-Services uses <b>SOAP</b> (<b>Simple Object Access Protocol</b>) as the standard protocol for transferring data between applications. SOAP is an <b>XML based protocol</b> for packing messages in XML format. Since SOAP is using XML to transfer data/messages between applications, it provides a lighter mechanism and that’s the reason why most of the Web-Services applications use <b>SOAP over HTTP</b> as the standard transport protocol for exchanging messages over the Internet, although Web-Services can easily mingle with any type of compliant protocols.</p>
<p><span style="text-decoration: underline;"><b>SOAP Specification</b></span></p>
<p>SOAP which is the standard protocol for Web-Services, is actually a standard given by <b>W3C </b>(World Wide-Web Consortium) Group.  The following section discusses the structure of  SOAP messages in greater detail.</p>
<p><span style="text-decoration: underline;"><b>The SOAP message</b></span></p>
<p>Communication between two heterogeneous systems using Web-Services can be achieved with the help of SOAP protocol by sending and receiving <b>SOAP messages</b>. A client construct a SOAP message, which is an XML based message with appropriate <a href="http://www.javabeat.net/articles/print.php?article_id=80#"><span style="color: blue;">XML schema</span></a> (<a href="http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>) and sending the message as a request message to the processing application. The processing application (which is usually a Web-Service) unpacks the message, performs the requested operation and returns the result back to the calling application in the form of SOAP response message.</p>
<p><span style="text-decoration: underline;"><b>Structure of a SOAP message</b></span></p>
<p>The SOAP message consists of the following parts namely, the <b>Envelope</b>, <b>Header</b> and the <b>Body</b>. Following diagram shows how a SOAP message looks like,</p>
<p><span style="text-decoration: underline;"><b>Envelope</b></span></p>
<p>From the above picture, one can infer that the <b>Envelope</b> forms the outer-most structure in a SOAP message and it acts as a container for both the <b>Header</b> and the <b>Body</b> Entries. The Envelope therefore forms a mandatory part in the SOAP message. Envelope doesn’t contain any of the data to be transmitted to the receiving application, but still it may contain the necessary meta-data of the sending and the receiving applications.</p>
<p>Following is how the envelope looks like in XML format,</p>
<pre class="brush: java; title: ; notranslate">

&lt;Soap:Envelope

xmlns:Soap=&quot;&lt;a href=&quot;http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;http://schemas.xmlsoap.org/soap/envelope/&lt;/a&gt;&quot;&gt;

….

&lt;/ Soap:Envelope&gt;

</pre>
<p>As we can see, the above Soap envelope declaration references the <b>name-space</b> from ‘http://schemas.xmlsoap.org/soap/envelope’. See more about <b>name-spaces</b> below. The name of the envelope element is ‘<b>Envelope</b>’ and the fully-qualified name (element name along with namespace prefix) is<b>Soap:Envelope</b>, where Soap is the namespace prefix.</p>
<p><i>[XML Namespaces – XML Namespaces are a way to avoid name collisions that may occur in the elements and attributes that are found in a XML document. Consider a situation where we want to represent a television monitor and a computer monitor in a XML file. Following may be one kind of representation for this,</i></p>
<pre class="brush: java; title: ; notranslate">

&lt;items&gt;

...

&lt;television&gt;

&lt;monitor inch=’14’/&gt;

&lt;/television&gt;

&lt;computer&gt;

&lt;monitor inch = ‘11’/&gt;

&lt;/computer&gt;

...

&lt;/items&gt;

</pre>
<p>In the above simple example, we have two monitor elements within television and computer elements both sharing the common name(‘monitor’). It may happen for the processing applications to spend a good deal of time, to find whether the parsed ‘monitor’ element belong to television or computer element by analyzing its root element. Situations may go even worse if both the monitor elements are at the same level.</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>So, to avoid these kinds of naming collisions within an XML document, XML namespaces were introduced. A namespace represents a collection of names and no two names within the namespace can be the same. Following represents the syntax to define a namespace in a XML document, xmlns:prefixId=’NamespaceIdentifer’.</p>
<p>The above syntax has 3 entities, namely the keyword name ‘xmlns’ (which stands for XML Namespace), the prefix which serves as a short-hand representation for the NamespaceIdentifier. Any kind of string can be given for NameSpaceIdentifer, but the preferred way is to give URL’s as no two URL’s in the world can be unique.</p>
<p>Now these namespace definitions have to be applied to the elements in such a way that the element’s name have to be prefixed with the prefix that we have already declared in the namespace definition.</p>
<pre class="brush: java; title: ; notranslate">

&lt;tele:television xmlns:tele=’http://www.mytelevisions.com’&gt;

&lt;tele:monitor inch=’14’/&gt;

&lt;/tele:television&gt;

</pre>
<p>The above modified element declared can be interpreted like this, a namespace called “http://www.mytelevisions.com” is created and it is given a prefix ‘tele’, After this all the elements within the television element are made namespace-aware by prefixing them with ‘tele’.</p>
<p>Now, the revised XML document will look similar to this,</p>
<pre class="brush: java; title: ; notranslate">

&lt;items&gt;

...

&lt;tele:television xmlns:tele=’http://www.mytelevisions.com’&gt;

&lt;tele:monitor inch=’14’/&gt;

&lt;/tele:television&gt;

&lt;comp:computer xmlns:tele=’http://www.mycomputers.com’&gt;

&lt;comp:monitor inch = ‘11’/&gt;

&lt;/comp:compuer&gt;

...

&lt;/items&gt;]

</pre>
<p><span style="text-decoration: underline;"><b>Header</b></span></p>
<p>The next optional element in the SOAP Envelope is the <b>header</b> element. If present, the element comes immediately after the <b>Envelope</b> element. The XML representation for the <b>Header</b> element looks like the following,</p>
<pre class="brush: java; title: ; notranslate">

&lt;Soap:Envelope

xmlns:Soap=&quot;&lt;a href=&quot;http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;http://schemas.xmlsoap.org/soap/envelope/&lt;/a&gt;&quot;&gt;

&lt;Soap:Header&gt;

…

&lt;/Soap:Header&gt;

&lt;Soap:Header&gt;

…

&lt;/Soap:Header&gt;

&lt;/Soap:Envelope&gt;

</pre>
<p>Any number of header elements can appear after the <b>Envelope</b> element. The <b>Header</b> element is used to provide some meaningful information to the receiving application. For example, a sender application can include the language and the currency information as part of the header information like this,</p>
<pre class="brush: java; title: ; notranslate">

&lt;Soap:Envelope

xmlns:Soap=&quot;&lt;a href=&quot;http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;http://schemas.xmlsoap.org/soap/envelope/&lt;/a&gt;&quot;&gt;

...

&lt;Soap:Header&gt;

&lt;language&gt;English&lt;/language&gt;

&lt;/Soap:Header&gt;

&lt;Soap:Header&gt;

&lt;currency&gt;INR&lt;/currency&gt;

&lt;/Soap:Header&gt;

...

&lt;/Soap:Envelope&gt;
</pre>
<p><span style="text-decoration: underline;"><b>Body</b></span></p>
<p>Unlike the optional header element, <b>Body</b> element is mandatory as it includes that actual data to be sent to the receiving application. The <b>body</b> element immediately follows the Envelope element -if there is no Header element, or it comes after the Header element.</p>
<pre class="brush: java; title: ; notranslate">

&lt; Soap:Envelope

xmlns:Soap=&quot;&lt;a href=&quot;http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;http://schemas.xmlsoap.org/soap/envelope/&lt;/a&gt;&quot;&gt;

&lt;Soap:Header&gt;

&lt;language&gt;English&lt;/language&gt;

&lt;/Soap:Header&gt;

&lt;Soap:Body xmlns:MyData=”http://mydata.com”&gt;

&lt;MyData:MyPersonalData&gt;

&lt;MyData:Name&gt;MyName&lt;/MyData:Name&gt;

&lt;MyData:Age&gt;MyAge&lt;/MyData:Age&gt;

&lt;/MyData:MyPersonalData&gt;

&lt;/Soap:Body&gt;

&lt;/Soap:Envelope&gt;

</pre>
<p>Note that in the above XML, a namespace called “<b><i>http://mydata.com</i></b>” is referenced and all the elements within the body like ‘<b><i>MyPersonalData</i></b>’, ‘<b><i>Name</i></b>’ and ‘<b><i>Age</i></b>’ are fully qualified as ‘<b><i>MyData:MyPersonalData’</i></b>, ‘<b><i>MyData:Name’</i></b> and ‘<b><i>MyData:Age</i></b>’ respectively.</p>
<p><span style="text-decoration: underline;"><b>SOAP messages with Attachments</b></span><b> </b></p>
<p>In many of the situations SOAP messages alone cannot be sufficient for data transmission between applications as a SOAP message can hold only textual representation of data. Say, an XML message can only hold a Customer Name, an Employee Id, or a Cricket Score. It cannot hold binary information like images, audio files or video files. In such a case, SOAP XML messages cannot always best represent the whole set of real-world data. To get rid-off the lacking functionality with SOAP, came the specification from W3C called “<b>Soap Messages with Attachments</b>”.</p>
<p>One can identify from the name that SOAP messages with Attachments are extensions to SOAP messages in that it can hold not only textual data (in the form of XML) but also other types of messages (like audio files, image files etc.,). Logically, SOAP messages with attachments can two different parts (or sections) namely<b>SOAP Part</b> and the <b>Attachment Part</b>, which is illustrated in the following diagram.</p>
<p><span style="text-decoration: underline;"><b>SOAP Implementation</b></span><b> </b></p>
<p>Different vendors have given implementation for the specification of SOAP given by W3C. Popular SOAP implementation (or products) includes, <b>SAAJ</b> (<b>S</b>OAP with<b>A</b>ttachments <b>A</b>PI for <b>J</b>ava) from Java, <b>IBM’s SOAP4J</b> (SOAP for Java) and <b>Microsoft’s SOAP Toolkit</b>. The following section presents a sample application for constructing a SOAP message using the <b>SAAJ API</b>.</p>
<p><span style="text-decoration: underline;"><b>Sample Application</b></span><b> </b></p>
<p>With the above basics like SOAP messages and attachments in mind, let us write a sample SOAP application in Java using<b>SAAJ API</b>. SAAJ, which stands for <b>SOAP with Attachments API for Java</b>, can be used to send XML messages along with Attachments between two applications. The entire API needed for sending and receiving SOAP messages are available in<b>javax.xml.soap</b>.</p>
<p>Let us use the API to construct a sample SOAP message. Though the API provides rich features like constructing, sending and receiving SOAP messages, this sample is limited in showing the construction of SOAP messages only. Listing shows the code to construct the SOAP message using the SAAJ API.</p>
<pre class="brush: java; title: ; notranslate">

SoapMessageConstruction.java:

package test;

import javax.xml.namespace.QName;

import javax.xml.soap.*;

public class SoapMessageConstruction {

public SoapMessageConstruction() {

}

public void construct(){

try{

MessageFactory messageFactory = MessageFactory.newInstance();

SOAPMessage message = messageFactory.createMessage();

// Add header entries here.

SOAPHeader soapHeader = message.getSOAPHeader();

// Application name header.

QName qNameForAppName = new QName(&quot;http://myApp.com&quot;, &quot;Bank-Name&quot;, &quot;app&quot;);

SOAPHeaderElement headerForAppName = soapHeader.addHeaderElement(qNameForAppName);

headerForAppName.addTextNode(&quot;ICICI Bank&quot;);

// Currency header.

QName qNameForCurrency = new QName(&quot;http://myApp.com&quot;, &quot;Currency&quot;, &quot;app&quot;);

SOAPHeaderElement headerForCurrency = soapHeader.addHeaderElement(qNameForCurrency);

headerForCurrency.addTextNode(&quot;INR&quot;);

// The SOAP part of the message.

SOAPPart soapPart = message.getSOAPPart();

SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

SOAPBody soapBody = soapEnvelope.getBody();

QName qNameForAccNo = new QName(&quot;http://myBank.com&quot;, &quot;Account-No&quot;, &quot;bank&quot;);

SOAPBodyElement elementForAccNo =

soapBody.addBodyElement(qNameForAccNo);

elementForAccNo.addTextNode(&quot;123456789&quot;);

QName qNameForTotalAmount = new QName(&quot;http://myBank.com&quot;, &quot;Total-Amount&quot;, &quot;bank&quot;);

SOAPBodyElement elementForTotalAmount =

soapBody.addBodyElement(qNameForTotalAmount);

elementForTotalAmount.addTextNode(&quot;75000.00&quot;);

message.writeTo(System.out);

}catch(Exception exception){

exception.printStackTrace();

}

}

public static void main(String args[]){

SoapMessageConstruction constructor = new SoapMessageConstruction();

constructor.construct();
}

</pre>
<p>The output for the above sample program is given below,</p>
<pre class="brush: java; title: ; notranslate">&lt;/pre&gt;
&lt;SOAP-ENV:Envelope

xmlns:SOAP-ENV=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;

&lt;SOAP-ENV:Header&gt;
&lt;app:Bank-Name xmlns:app=&quot;http://myApp.com&quot;&gt;

ICICI Bank

&lt;/app:Bank-Name&gt;

&lt;app:Currency xmlns:app=&quot;http://myApp.com&quot;&gt;

INR

&lt;/app:Currency&gt;


&lt;/SOAP-ENV:Header&gt;


&lt;SOAP-ENV:Body&gt;

&lt;bank:Account-No         xmlns:bank=&quot;http://myBank.com&quot;&gt;123456789&lt;/bank:Account-No&gt;

&lt;bank:Total-Amount xmlns:bank=&quot;http://myBank.com&quot;&gt;75000.00&lt;/bank:Total-Amount&gt;

&lt;/SOAP-ENV:Body&gt;

&lt;/SOAP-ENV:Envelope&gt;
&lt;pre&gt;</pre>
<p>Let us see the various pieces of code in detail.</p>
<pre class="brush: java; title: ; notranslate">&lt;/pre&gt;
MessageFactory messageFactory = MessageFactory.newInstance();

SOAPMessage message = messageFactory.createMessage();

</pre>
<p>The initial point of entry to construct a SOAP message is to depend on the <b><i>MessageFactory</i></b> class which is a factory class to create SOAP messages. The <b><i>createMessage()</i></b>  method creates and returns a new instance of the SOAP message. The very good thing is that as soon as a SOAP message is created, the inner elements like envelope, header and body are created by default. Printing the SOAP message object to the console  (by calling <b><i>message.writeTo(System.out)</i></b>) will result in an output like this,</p>
<pre class="brush: java; title: ; notranslate">

&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;

&lt;/SOAP-ENV:Envelope&gt;

// Add header entries here.

SOAPHeader soapHeader = message.getSOAPHeader();

// Application name header.

QName qNameForAppName =

new QName(&quot;http://myApp.com&quot;, &quot;Bank-Name&quot;, &quot;app&quot;);

SOAPHeaderElement headerForAppName =

soapHeader.addHeaderElement(qNameForAppName);

headerForAppName.addTextNode(&quot;ICICI Bank&quot;);

&amp;nbsp;

// Currency header.

QName qNameForCurrency =

new QName(&quot;http://myApp.com&quot;, &quot;Currency&quot;, &quot;app&quot;);

SOAPHeaderElement headerForCurrency =

soapHeader.addHeaderElement(qNameForCurrency);

headerForCurrency.addTextNode(&quot;INR&quot;);

</pre>
<p>The next section of the code gets the header element of the SOAP message by calling<b><i>message.getSOAPHeader()</i></b> and adds some header entries to it. It does so by calling the<b><i>SOAPHeader.addHeaderElement(QName)</i></b> method (See more about QName below.) which adds an empty element called “Bank-Name”. The Bank-Name element is populated with some text content by calling the<b><i>SOAPHeaderElement.</i></b><b><i>addTextNode(String)</i></b> method. The above code will result in populating the message structure like this,</p>
<pre class="brush: java; title: ; notranslate">

&lt;b&gt;&lt;i&gt;QName – QName which stands for qualified name represents the fully qualified name for an xml element, Consider the following xml,&lt;/i&gt;&lt;/b&gt;&lt;b&gt;&lt;i&gt;&lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt; &lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt;&lt;cricket:player xmlns:cricket = “&lt;a href=&quot;http://web.archive.org/web/20080116132744/http://www.cricket.com/&quot;&gt;http://www.cricket.com&lt;/a&gt;”&gt;&lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt;            &lt;name&gt;….&lt;/name&gt;&lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt;&lt;/cricket:player&gt;&lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt; &lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt;&lt;football:player xmlns:football = “&lt;a href=&quot;http://web.archive.org/web/20080116132744/http://www.football.com/&quot;&gt;http://www.football.com&lt;/a&gt;”&gt;&lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt;            &lt;name&gt;….&lt;/name&gt;&lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt;&lt;/football&gt;&lt;/i&gt;&lt;/b&gt;

</pre>
<p><b><i>We have two player elements here, However, with the help of XML name-spaces, they are fully qualified as cricket:player and football:player. For the cricket:player, the element name is “player”, the prefix is “cricket” and the reference name-space is “<a href="http://web.archive.org/web/20080116132744/http://www.cricket.com/">http://www.cricket.com</a>”.</i></b></p>
<p><b><i>This fully qualified name representation forms the QName for an element, For example, the above xml code is logical equivalent to the following java code,</i></b></p>
<pre class="brush: java; title: ; notranslate">

&lt;b&gt;&lt;i&gt;QName qNameForCricketPlayer = new QName(“&lt;a href=&quot;http://web.archive.org/web/20080116132744/http://www.cricket.com/&quot;&gt;http://www.cricket.com&lt;/a&gt;”, “player”, “cricket”);&lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt; &lt;/i&gt;&lt;/b&gt;

&lt;b&gt;&lt;i&gt;QName qNameForFootballPlayer = new QName(“&lt;a href=&quot;http://web.archive.org/web/20080116132744/http://www.cricket.com/&quot;&gt;http://www. football.com&lt;/a&gt;”, “player”, “football”);&lt;/i&gt;&lt;/b&gt;

</pre>
<p><b><i>The first three arguments in the constructor refers to the name-space URI, the element name and the prefix respectively</i></b><b><i>]</i></b></p>
<pre class="brush: java; title: ; notranslate">

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;SOAP-ENV:Envelope&lt;/b&gt;

&lt;b&gt;xmlns:SOAP-ENV=&lt;/b&gt;&lt;b&gt;&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;&lt;b&gt;

&lt;SOAP-ENV:Header&gt;&lt;/b&gt;

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;app:Bank-Name &lt;/b&gt;&lt;b&gt;xmlns:app=&lt;/b&gt;&lt;b&gt;&quot;http://myApp.com&quot;&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;

&lt;b&gt;ICICI Bank&lt;/b&gt;

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;/app:Bank-Name&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;&lt;b&gt;

&lt;app:Currencyxmlns:app=&quot;http://myApp.com&quot;&gt;&lt;/b&gt;

&lt;b&gt;INR&lt;/b&gt;

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;/app:Currency&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;&lt;b&gt;        &lt;/b&gt;

&lt;b&gt; &lt;/b&gt;

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;/SOAP-ENV:Header&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;

&lt;b&gt; &lt;/b&gt;

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;/SOAP-ENV:Envelope&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;

&amp;nbsp;

&amp;nbsp;

&lt;b&gt;// The SOAP part of the message.&lt;/b&gt;&lt;b&gt;&lt;/b&gt;

&lt;b&gt;SOAPPart soapPart = message.getSOAPPart();&lt;/b&gt;

&lt;b&gt;SOAPEnvelope soapEnvelope = soapPart.getEnvelope();&lt;/b&gt;

&lt;b&gt;SOAPBody soapBody = soapEnvelope.getBody();&lt;/b&gt;

&lt;b&gt;           &lt;/b&gt;

&lt;b&gt;QName qNameForAccNo = new QName(&quot;http://myBank.com&quot;, &quot;Account-No&quot;, &quot;bank&quot;);&lt;/b&gt;

&lt;b&gt;SOAPBodyElement elementForAccNo =&lt;/b&gt;

&lt;b&gt;soapBody.addBodyElement(qNameForAccNo);&lt;/b&gt;

&lt;b&gt;elementForAccNo.addTextNode(&quot;123456789&quot;);           &lt;/b&gt;

&lt;b&gt; &lt;/b&gt;

&lt;b&gt;QName qNameForTotalAmount = new QName(&quot;http://myBank.com&quot;, &quot;Total-Amount&quot;, &quot;bank&quot;);&lt;/b&gt;

&lt;b&gt;SOAPBodyElement elementForTotalAmount =&lt;/b&gt;

&lt;b&gt;soapBody.addBodyElement(qNameForTotalAmount);&lt;/b&gt;

&lt;b&gt;elementForTotalAmount.addTextNode(&quot;75000.00&quot;);           &lt;/b&gt;

</pre>
<p>Similarly, the elements within the body content are added using the above code. Now the resultant SOAP message will look similar to this,</p>
<p><b> 
<pre class="brush: java; title: ; notranslate">&lt;/b&gt;

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;SOAP-ENV:Envelope &lt;/b&gt;&lt;b&gt;xmlns:SOAP-ENV=&lt;/b&gt;&lt;b&gt;&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;&lt;b&gt;

&lt;SOAP-ENV:Header&gt;

&lt;app:Bank-Name xmlns:app=&quot;http://myApp.com&quot;&gt;&lt;/b&gt;

&lt;b&gt;ICICI Bank&lt;/b&gt;

&lt;b&gt;&lt;&lt;/b&gt;&lt;b&gt;/app:Bank-Name&lt;/b&gt;&lt;b&gt;&gt;&lt;/b&gt;&lt;b&gt;
&lt;app:Currency xmlns:app=&quot;http://myApp.com&quot;&gt;INR&lt;/app:Currency&gt;

&lt;/SOAP-ENV:Header&gt;


&lt;SOAP-ENV:Body&gt;

&lt;bank:Account-No xmlns:bank=&quot;http://myBank.com&quot;&gt;123456789&lt;/bank:Account-No&gt;
&lt;bank:Total-Amount xmlns:bank=&quot;http://myBank.com&quot;&gt;75000.00&lt;/bank:Total-Amount&gt;

&lt;/SOAP-ENV:Body&gt;

&lt;/SOAP-ENV:Envelope&gt;&lt;/b&gt;

</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/07/ejb-3-webservices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate Vs EJB 3.0</title>
		<link>http://www.javabeat.net/2008/04/hibernate-vs-ejb-3-0/</link>
		<comments>http://www.javabeat.net/2008/04/hibernate-vs-ejb-3-0/#comments</comments>
		<pubDate>Thu, 10 Apr 2008 12:20:07 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>
		<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=176</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>Originally published in DeveloperIQ magazine What is CMP and BMP in EJB? So, why is it that Entity beans alone were found wanting and the specification keeps on changing? Entity beans are of two types. CMP &#38; BMP. CMP stands for Container-Managed Persistence and BMP stands for Bean-managed persistence. Theoretically, the EJB specification does not [...]</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><em>Originally published in <a href="http://www.developeriq.com/">DeveloperIQ</a> magazine</em></p>
<h2>What is CMP and BMP in EJB?</h2>
<p>So, why is it that Entity beans alone were found wanting and the specification keeps on changing? Entity beans are of two types. CMP &amp; BMP. CMP stands for Container-Managed Persistence and BMP stands for Bean-managed persistence. Theoretically, the EJB specification does not say anything about the method to be adopted in persisting objects for permanent storage and retrieval. It could be simple object serialization. The database may be object-database or Object-relational database or XML.In practice , however, a database has always meant a Relational Database and its SQL.</p>
<p>In a very complex Enterprise application, we begin with Modelling. Instead of dealing with tables and their complex inter-relations, it is more intuitive to deal with classes and objects. Thus we design our system , &#8216;thinking in objects&#8217; and not in tables. So long, as we are dealing with objects in memory or with objects persisted in hard-disk simply as objects, there is no problem, except that object-serialization , especially of complex objects is a slow process. On the other-hand, Relational Database technology is fast, time-tested, well-known and famous. So, the problem is to work with objects in memory but persist the objects in hard disk as relational database.</p>
<p>This is what is known as ORM ( Object-Relational Mapping).If we opt to deal directly with tables only and either read data or manipulate data by session beans, we skip the entire ORM problem. But how practical is it for really complex projects? That is the rationale for the development of Entity Beans in EJB.</p>
<p>In CMP, the coder deals with objects, only in memory. He creates new objects, modifies them, deletes them and views them , all in memory. The task of saving these objects in memory ,to the relational database table is done by the container, automatically. The coder does not write any sql-related code for this.</p>
<p>In BMP, the coder has to write the sql to persist the object in memory to the relational database.</p>
<p>CMP in EJB1.1 was suitable for simple tables, without complex relationships to other tables. CMP avoids all references to the underlying database. So, it is more portable. There is no vendor-lock-in. CMP can persist data to Object- databases also, besides Relational databases.</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>But, CMP is not always suitable. If the database is some legacy type, which cannot be used with SQL, the database company gives a proprietary code for persistence and such code has to be used in our program to persist data. The facilities given in CMP originally were found to be too elementary and there were complaints.</p>
<p>But, what matters is that CMP makes use of ORM concepts, though the implementation left much to be desired. It did not expose how the EJB vendor implements it. Weblogic, Oracle, IBM WebSphere, SUN , JBoss , each may implement CMP in any way that they deem fit. Except in special circumstances, it will be better to use CMP, not merely because, it makes the code more portable &amp; is easy to write. Much more important reason is that the EJB container can optimize the performance dramatically, if we adopt CMP. So the developer community wanted to adopt CMP but found it unsuitable for really complex jobs.</p>
<p>And a sizable section of developers found the XML Deployment Descriptors for CMP ,especially for complex jobs, a bit troublesome and tedious.It can be said that any design which makes us dependent on wizards, is a bad design. Unlike the Deployment Descriptors for Session beans, which can be hand-coded in a jiffy, by just find/replace method in a text editor, the DD for CMP required three XML files, two of them very special to the container used.</p>
<p>In order to improve things, EJB 2.0 proposed a few changes, mainly in the matter of writing CMP. It provided for Relationships. It proposed a simple query language known as &#8216;EJB-QL&#8217;. Since, calling an Entity bean through a session bean (Facade pattern) is more efficient , from the viewpoint of minimizing network traffic, the very concept of remote interface for entity beans was questioned and so local interface also was provided for Entity beans.( In a total reversal, there is no local interface in EJB-3! and instead of EJB-QL , Hybernate Query Langauge is taking over in EJB-3).</p>
<p>Even with all these improvements, CMP was found to be less than the ultimate solution. There was no possibility for Inheritance.</p>
<p>Though the container services provided by the EJB container are indispensable in a truly large enterprise application, the J2EE camp is almost vertically split into WebTier &amp; EJB-Tier votaries. The WebTier supporters claim that EJB with its steep learning curve and error prone development environment for developers is not really necessary for most applications. And they would like to have an ORM tool , built into the J2EE specification. For after all, ORM task is not specific to EJB alone. Even Servlets and JSP could use them. In fact , they have been using them, though the J2EE specification was silent about it. ORM tools like OJB, JDO and Hibernate can be used not only in EJB containers but in webcontainer and even in standalone containers. Gavin King makes it a special point in favour of Hibernate. Making such a tool , a J2EE standard, would make development tasks far easier ,to develop either web-tier application or ejb-tier application, saving us from the medley of classpath to required jars.</p>
<p>In a scathing attack on the complexity and questionable performance of EJB Entity beans (though, unjustifiably on EJB itself), Rod Johnson,prophesies , that in a few years&#8217; time, J2EE will cease to include EJB. Whether , we agree or not, it is worth looking into the criticisms against EJB Entity beans ,raised by him.( &#8216;J2EE Development without EJB&#8217;-Wrox/Wiley/DreamTech-2004).For, he is proposing the Spring Framework as an alternative to EJB container and the idea is gaining ground.J2EE developers and students may have to re-orient themselves rather abruptly, to remain relevant to industry.</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/04/hibernate-vs-ejb-3-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EJB 3.0 Timer Services</title>
		<link>http://www.javabeat.net/2007/03/ejb-3-0-timer-services-an-overview/</link>
		<comments>http://www.javabeat.net/2007/03/ejb-3-0-timer-services-an-overview/#comments</comments>
		<pubDate>Wed, 28 Mar 2007 04:25:25 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7</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 Starting from EJB 2.1, Timer Services are available for building J2EE Applications that depends on time based services. Time based services are mostly used in scheduling applications. Technically, these scheduling applications are called workflows. A workflow defines a configurable sequence of activities or tasks that will take place at a particular point of time. [...]</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>Starting from EJB 2.1, Timer Services are available for building J2EE Applications that depends on time based services. Time based services are mostly used in scheduling applications. Technically, these scheduling applications are called workflows.</p>
<p>A workflow defines a configurable sequence of activities or tasks that will take place at a particular point of time. Before EJB 2.1, one has to manually code for building and deploying time-based workflow systems. But, with the invent of <strong>EJB 3.0</strong>, thanks to Annotations and Dependency injections, life has become still more easier for creating such applications.</p>
<h2>What are Timer Services?</h2>
<p>Consider a reporting Application, that will send report in the form of mails, every Monday, or a Billing Service that sends credit or debit bills on the 1st of every month. These applications depend on time-based events. To be more precise, these applications should allow developers to schedule some business logic or process so that they can be executed at some regular intervals of time. This is the core concept behind EJB Timers.</p>
<p><strong>EJB Timer Services</strong> are services that are provided by the container (or the Application Server) and developers can take advantage of the timer services by registering one or more enterprise beans for time-based notification.</p>
<h2>Different Types of Timers:</h2>
<p>EJB basically supports two forms of Timer objects:</p>
<ul>
<li>Single Action Timer</li>
<li>Interval Timer</li>
</ul>
<h3>a) Single Action Timer</h3>
<p>A single action timer (or a single interval timer) is a one which will expire only once (as opposed to interval timer, where multiple expirations are possible).</p>
<p>Accordingly EJB supports two different ways for constructing a single interval timer.</p>
<p>i) One is to create the timer in such a way that it will expire at a particular point of time which is specified as a Date</p>
<p>ii) The other possible way is make the timer to expire after certain period of time (say after 10 hours or 1 day) which is usually specified in milliseconds. After the timer expires, the enterprise bean will receive a kind of notification, i.e the container will call the ejbTimeout() method (or the method that is annotated with @Timeout annotation).</p>
<h3>b) Interval Timer</h3>
<p>Interval timer (or multiple action timer), as its name suggests will recur (or happen) at multiple intervals of time. That is, these kinds of timer will have multiple expirations at regular intervals of time.</p>
<p>Two different ways of constructing the Timers are available:</p>
<p>i) The first approach is to create a timer to have an initial expiration at some point of time (which is usually specified as a Date) and to have the subsequent expirations happen at a specified interval.</p>
<p>ii) The second approach is to construct the timer whose initial expiration will happen after an elapsed duration of time (in milliseconds) and to have the subsequent expirations happen after a specific interval. For every expirations of the Timer object, the container continues to call the ejbTimeout() method (or the method that is annotated with @Timeout annotation) until the bean explicitly calls the cancel() method.</p>
<h2>Timer Services API</h2>
<p>The <strong>Timer Services API</strong> is small and has only 4 interfaces packaged with it. It is expected that more API related to Timer Services will be added in the future EJB specification. The interfaces are:</p>
<ul>
<li>TimerService</li>
<li>Timer</li>
<li>TimedObject</li>
<li>TimerHandle</li>
</ul>
<h3>a) TimerService</h3>
<p>This interface provides support for creating timers (single-action or interval) as well as retrieving the existing timers (that are created by one or more enterprise beans) from the container. Enterprise beans can use this interface for creating single-action or interval timer objects.</p>
<p><strong>i) For creating timers</strong></p>
<ul>
<ul>
<li>Single-action Timers</li>
</ul>
</ul>
<p>The following two methods are available in the TimerService API for creating a single action timer:</p>
<ul>
<ul>
<ul>
<li>Timer createTimer(long duration, Serializable info)</li>
<li>Timer createTimer(Date expiration, Serializable info)</li>
</ul>
</ul>
</ul>
<p>Using the first method, a single action timer can be made to expire after a specified duration of time. The second method will be useful if the timer is needed to expire at a particular point of time. The second argument in both the versions will be useful, if application specific information has to be passed to the Timer objects, else it can be safely ignored by passing null.</p>
<ul>
<ul>
<li>Interval Timers</li>
</ul>
</ul>
<p>Following are the ways to create an interval based timer object.</p>
<ul>
<ul>
<ul>
<li>Timer createTimer(long initialDuration, long intervalDuration, Serializable info)</li>
<li>Timer createTimer(Date initialExpiration, long intervalDuration, Serializable info)</li>
</ul>
</ul>
</ul>
<p>Interval timers have options to specify the initial expiration in the form of milliseconds or as a Date object and the subsequent expirations can be expressed in milliseconds. In the first version, the initial expiration for the Timer object will happen after the initialDuration has elapsed and subsequent expirations will happen at the specified intervalDuration. The second version supports in specifying the initial time of expiration as a Date object and the rest of the information is the same as that of the first version. Similar to single action timers, these timers also allows the enterprise beans to pass application specific information.</p>
<p><strong> ii) For iterating over the existing timers</strong></p>
<p>Collection getTimers() – This method will return a collection of timers that were already created by other enterprise beans that may be in different parts of the system.</p>
<h3>b) Time</h3>
<p>This interface holds information about the timer objects that was previously created by enterprise beans.</p>
<ul>
<ul>
<li><em>Serializable getInfo ()</em></li>
</ul>
</ul>
<p>Returns the application specific object that was passed previously by the enterprise beans while creating timer objects. The object must implement the Serializable interface.</p>
<ul>
<ul>
<li><em>Date getNextTimeout()</em></li>
</ul>
</ul>
<p>Returns the time (as a Date object) that tells when the next expiration is going to happen for this timer object.</p>
<ul>
<ul>
<li><em>long getTimeRemaining()</em></li>
</ul>
</ul>
<p>Returns the number of remaining milliseconds that is left before the next expiration happens for this timer.</p>
<ul>
<ul>
<li><em>TimerHandle getHandle()</em></li>
</ul>
</ul>
<p>Returns an instance of TimerHandle object which at a later time can be used to reconstruct the Timer object.</p>
<ul>
<ul>
<li><em>void cancel()</em></li>
</ul>
</ul>
<p>Cancels the timer object. After cancellation, enterprise beans that have already registered for getting time-based notification (through the ejbTimeout() method) will no longer receive events.</p>
<h3>c) TimedObject</h3>
<p>Enterprise beans can implement this interface to receive time-based notifications (or callbacks) on Timer objects. The ejbTimeout() method will be invoked by the container whenever the timer expires.</p>
<p>For a single action timer, the ejbTimeout() will be called only once, whereas for an interval timer, this callback method may be called multiple times.</p>
<p><em>void ejbTimeout(java.ejb.Timer timer)</em></p>
<p>This method is called by the EJB Container when the timer object has expired.</p>
<p>There are two possible ways for implementing a call back method:</p>
<ul>
<li>One way is to make the enterprise bean implement the TimedObject interface and to give an implementation for the ejbTimeout(Timer timer) method. For example,
<pre class="brush: java; title: ; notranslate">@Stateless
@Remote
class MyBeanImpl implements MyBean, TimedObject{
Public void ejbTimedout(Timer timer){
.
.

}

}</pre>
</li>
<li>The other way is to annotate a method that is defined within the enterprise bean class with the @Timeout annotation. In this case, there is no need for the enterprise bean to implement the TimedOut interface. The return type of this method must be void and it should accept only one argument of type Timer.
<pre class="brush: java; title: ; notranslate">@Stateless
@Remote
class MyBeanImpl implements MyBean{
@Timeout
public void myTimedOutMethod(Timer timer){
....
}
}</pre>
</li>
</ul>
<h3>d) TimerHandle</h3>
<p>This interface is implemented by the container so that enterprise beans at a later point can use this handle to reconstruct the timer object. TimerHandle extends the Serializable interface. So, the clients may serialize the handle. Because of this, TimerHandle are local objects, hence it is illegal to pass this object as an argument to remote interfaces.</p>
<p><em>Timer getTimer()</em></p>
<p>Obtains a reference to the Timer object.</p>
<h2>Timer Operations</h2>
<p>The following summarizes the various timer operations that may happen once a timer object is created:</p>
<ul>
<li>Creation</li>
<li>Cancellation</li>
<li>Expiration</li>
</ul>
<h2>Creating Timer Objects</h2>
<p>Timer objects are usually created by one or more enterprise beans. Only stateless session beans and message-driven beans can create timer objects. The reason why stateful session beans cannot create timer objects is not clear in the specification. So, as of now, creating timer objects within stateful session beans will result in IllegalStateException. However, it is expected that the future specifications may also mandate stateful session beans to support timers.</p>
<p>Here is the sequence of steps to be followed for creating a Timer object.</p>
<p>a) Get a reference to the EJBContext object (for session beans it is SessionContext and for message-driven beans, MessageDrivenContext is used).</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>b) Obtain a reference to the TimerService using the context object.</p>
<p>c) Create single action or multiple Timer objects using the TimerService object.</p>
<h3>a) Getting a Reference to the Context object</h3>
<p>With the new EJB 3.0 way, getting a reference to the Context object with the help of Annotation and Dependency Injection has become easy. Following is a sample code to get a reference to the SessionContext (in the case of session beans) and MessageDrivenContext (in the case of message driven beans).</p>
<pre class="brush: java; title: ; notranslate">@Resource
	Private SessionContext sessionCtx;
	@Resource
	Private MessageDrivenContext messageDrivenCtx;</pre>
<p>When the container creates an instance of enterprise beans, it will process all the annotations that are listed and then perform a dependency injection. So, the result is that sessionCtx reference and the messageDrivenCtx will be populated with an instance of type SessionContext and MessageDrivenContext respectively.</p>
<h3>b) Getting a Reference to TimerService:</h3>
<p>Getting a reference to the TimerService object is relatively simple, just a call to Context.getTimerService() will do that, like this</p>
<pre class="brush: java; title: ; notranslate">TimerService timerService = sessionCtx.getTimerService();
	TimerService timerService = messageDrivenCtx.getTimerService();</pre>
<h3>c) Creating Timer objects:</h3>
<p>As discussed earlier, timers are of two kinds. Single-action and Interval timer, Depending on the requirement, create any of the two variations of the timer objects. Given below are some samples for creating different timer objects with different configurations.</p>
<p>i) A timer object that will expire after 10 seconds from now.</p>
<pre class="brush: java; title: ; notranslate">
Calendar now = Calendar.getInstance();
Timer timer = timerService.createTimer(now.getTimeInMillis()
            + (10 * 1000), null);</pre>
<p>ii) This timer object will expire on the 1st of March 2007.</p>
<pre class="brush: java; title: ; notranslate">
Calendar firstMarch2007 = new GregorianCalendar(2007,
                                      Calendar.MARCH, 1);
Timer timer = timerService.createTimer(firstMarch2007, null);
</pre>
<p>iii) Here, the timer object initially expires after 1 week of time and subsequent expirations will happen after two weeks of time.</p>
<pre class="brush: java; title: ; notranslate">
long oneWeek = (7 * 24 * 60 * 60 * 1000);
Timer timer = timerService.createTimer(oneWeek,
                (oneWeek * 2), null);
</pre>
<p>iv) Here, the timer has an initial expiration that happens on the 1st of March 2007 and subsequent expirations will happen after one week of time.</p>
<pre class="brush: java; title: ; notranslate">
Calendar firstMarch2007 = new GregorianCalendar(2007,
                                 Calendar.MARCH, 1);
long oneWeek = (7 * 24 * 60 * 60 * 1000);
Timer timer = timerService.createTimer(firstMarch2007,
                                    oneWeek, null);
</pre>
<h3>Canceling the Timer</h3>
<p>Following are the three possible ways where a timer object can be made to cancel:</p>
<p><strong><br />
i) By explicitly calling the cancel method:<br />
</strong></p>
<p>When the enterprise beans decides that they no longer want to receive any kind of notifications (via. ejbTimeout (Timer) method), then can call the cancel method in the Timer object. Upon invoking this method, the enterprise beans that have previously registered for getting notifications will no longer will receive callbacks(i.e the ejbTimeout() method wont be called anymore) from the container.</p>
<pre class="brush: java; title: ; notranslate">Timer timer = timerService.createTimer(…);
	.
	.
	.
	timer.cancel();</pre>
<p><strong><br />
ii) When the timer object expires naturally:<br />
</strong></p>
<p>Timer expiration is applicable only for single action timers (as interval timer will never expire, the only way to stop from further functioning is to explicitly call the cancel() method). Expiration for single action timers happen when the time (mentioned in the form of milliseconds) has elapsed, or the time (mentioned in the form of a Date object) duration is over.</p>
<h3>Timer Expiration</h3>
<p>Timer expirations can happen in any of the three cases:</p>
<ul>
<li>The given date (and time) has arrived.</li>
<li>The period of time (that is given in the form of milliseconds) has elapsed.</li>
<li>The recurring interval has expired (in the case of interval timer).</li>
</ul>
<h2>Persistence</h2>
<p>Timers are persistent objects. To be precise, they are permanent objects. Whenever an enterprise bean creates an instance of a Timer object by using the TimerService, the TimerService will persist the Timer object by storing it in a database. Even if the server is abruptly terminated or it goes off, the timers will still be available and will become active once the server come backs to it normal state.</p>
<h2>Timers and Transactions</h2>
<p>Creating and canceling timers objects are made within a transactional context. So, if the transaction rolls back after creating a timer object, then the timer object creation is also rollbacked. Similarly, if the cancel method is called and the transaction is rolled back subsequently, the cancellation of the timer object is also rolled back.</p>
<h2>Sample Implementation</h2>
<p>Given below is a sample implementation that shows how an enterprise bean can use the facilities provided by the EJB Timer Services. Though, it is not a real time application, it may still provide the basic concepts that are back grounding the EJB Timer Services.</p>
<h3>i) Scenario</h3>
<p>This application is all about an employee who is giving status update to his manager at regular intervals. Though, the figures (startDate, endDate and the interval duration) and the status information may not mimic the real data, it may still provide a valuable way for writing a simple timer based application.</p>
<h3>ii) Identified Objects</h3>
<p><strong> a) Worker:<br />
</strong></p>
<p>Since Employee and Manager are really workers in a company, the purpose of this Worker class is to serve as a base class for the Employee and Manager class. It contains the common properties/attributes like name and id with its associated behavior.<strong><br />
b) Employee:<br />
</strong></p>
<p>This class represents an employee object apart from inheriting the properties like name and id from its base class Worker, it contains a static method getStatusString() that randomly returns some status update message.<strong><br />
c) Manager:<br />
</strong></p>
<p>Manager class that extends Worker class, apart from inheriting the common functionality, provides methods like reportStatus(Employee, status) that will accumulate the employee and his/her status information. It also has a printEmpStatusInfo() method, that will print all the status information of the employees for a particular duration of time.<strong><br />
d) StatusInfo:<br />
</strong></p>
<p>StatusInfo is an information holder class that holds information about the employee and the manager objects and also the low-level information like the startDate, endDate, intervalDuration that will be used by the Bean for creating timer objects and publishing status information.<strong><br />
e) StatusUpdateBean:<br />
</strong></p>
<p>The Local and the Remote Interfaces are represented by StatusUpdateLocal and StatusUpdateRemote respectively and the bean implementation is given by StatusUpdateBean. The remote interface has a method called setUpStatusInfo(StatusInfo) which is the only visible method as far as the client is concerned. Before invoking this method, the client (whether a stand-alone client, or a servlet ..), has to populate the StatusInfo object with relevant information like creating some test data representing the manager/employee objects, startDate/endDate/duration that represents when the employee has started giving status update to his manger, till what time he has to keep giving his updates, and the interval duration between the status updates.<strong><br />
f) Client:<br />
</strong></p>
<p>The client gets a reference to the Remote interface through dependency injection (or through a JNDI lookup), populates the StatusInfo object with some test objects before calling the setUpStatusInfo(StatusInfo) method.</p>
<h3>How it works</h3>
<p>Once the setUpStatusInfo(StatusInfo) method is called, the Bean creates an instance of the Timer object using the TimerService factory interface which is obtained through the SessionContext object (via. Dependency Injection).</p>
<pre class="brush: java; title: ; notranslate">
// Populates the SessionContext object using dependency injection.
@Resource
private SessionContext sessionContext;
// Obtain a reference to the TimerService object
TimerService timerService = sessionContext.getTimerService();
// Creates a timer object using the relevant information taken
//from the StatusInfo object.
// The following code creates a interval timer object with the
//specified startDate and with the duration
// as its interval.
Calendar startDate = statusInfo.getStartDate();
long duration = statusInfo.getNextInterval();
Timer timer = timerService.createTimer(startDate.getTime(),
                            duration, null);
</pre>
<h3>Timedout Method</h3>
<p>One can easily figure out that the updateStatus(Timer) is the timedout method for this enterprise bean as it is annotated with the @Timeout annotation. Within the method, the manager and the employee objects are obtained from the StatusInfo object and some dummy status is published to the manager object by calling the reportStatus(Employee, status) method. The manager objects keeps on storing the status against the employee object in a map. The method will be called infinitely if the timer object is not cancelled, since it is an interval timer. The timer is cancelled by checking whether the current time has crossed beyond the end time. If that’s the case, the timer object is cancelled and the status information for the employees is printed in the console.</p>
<pre class="brush: java; title: ; notranslate">
Code snippet …
@Timeout
public void updateStatus(Timer timer){
   Manager manager = statusInfo.getManager();
   List employees = statusInfo.getEmployees();
   for(int i=0; i
        System.out.println(&quot;Updating the Status Information..&quot;);
	manager.reportStatus(employees.get(i),
                        Employee.getStatusString());
   }
   Calendar now = new GregorianCalendar();
   if(now.after(statusInfo.getEndDate())){
   manager.printEmpStatusInfo();
    timer.cancel();
   }
}
</pre>
<h2>Conclusion</h2>
<p>Developers can take the advantage of the EJB Timer Services for building robust scheduling applications. One thing to remember is that, to be honest, developers are not encouraged to depend on Timer Services for building real-time applications (mission critical applications), as the expiration may not happen accurately at all times because of certain factors like the network latency, underlying implementation etc. Though, the timer services API is not exhaustive, it is believed that more and new functionalities will be added in the next specification of the EJB.</p>
<h2>Frequently asked Questions on Timer Services</h2>
<p>Q: a) What are Timer Services:</p>
<p>A: <strong>EJB Timer Services</strong> are container provided services for building scheduling (time-based) applications</p>
<h3>Q: b) What are the two different types of Timers and how they are useful?</h3>
<p>A: Timer comes in two forms. One is the single action timer and the other is interval timer. The former can be used in applications wherein which some logic has to be executed only once at a particular point of time (or after a specific duration) while the latter can be used to execute repeated logic at regular intervals.</p>
<h3>Q: c) What is the use of @Timeout() annotation in EJB 3.0?</h3>
<p>A: @Timeout() annotation when applied to a method will indicate that the method is a callback method for timer expirations and the container will call this method automatically whenever the timer object expires.</p>
<h3>Q: d) How to pass application specific information to timer objects?</h3>
<p>A: The createTimer() method (for both a single action and an interval timer) has an argument called info of type Serializable. This argument can be used to pass application specific information to timer objects (say, creditCardNumber and expiryDate in the case of Credit Card Processing System).</p>
<h3>Q: e) What necessary steps are involved for creating a timer object?</h3>
<p>A: Since timer services are container managed, we have to depend on the context object (EJBContext to be more specific) to make use of it. For a session bean, it is a SessionContext object and for a message driven bean, a MessageDrivenContext is used. Then, using the Context object, obtain a reference to the TimerService object. This TimerService factory object can then be used to create timers with different configurations.</p>
<h3>Q: f) What different situations are there to make a timer object to expire?</h3>
<p>A: A timer object can expire when the following conditions are met.</p>
<p>i) When the enterprise bean, explicitly calls the cancel() method, (in this case, the ejbTimeout(Timer) callback method will never be called.</p>
<p>ii) When the duration that is mentioned during the creation of the timer object has expired, or the specified time (mentioned in the form of a Date object) has reached.</p>
<p>iii) The interval duration has elapsed in the case of an interval timer (in which case, multiple expirations may be possible).</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/03/ejb-3-0-timer-services-an-overview/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
