<?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</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/ejb/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Working with Message-Driven Beans</title>
		<link>http://www.javabeat.net/2011/04/working-with-message-driven-beans/</link>
		<comments>http://www.javabeat.net/2011/04/working-with-message-driven-beans/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 15:11:33 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=623</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><a id="dd_start"></a><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;">Working with Message-Driven Beans</h1>
<h2>Introduction</h2>
<p><strong>Message-driven beans (MDBs)</strong> are EJB components designed to consume asynchronous messages. Although <strong>MDBs</strong> are intended to handle many different kinds of messages, we’ll discuss <strong>MDBs</strong> that process <strong>JMS</strong> messages because that is what MDBs are most commonly used for.</p>
<h2>JCA connectors and messaging</h2>
<p>Although by far <strong>JMS</strong> is the primary messaging provider for <strong>MDBs</strong>, as of EJB 2.1, it is not the only one. Thanks to the <strong>Java EE Connector Architecture (JCA)</strong>, <strong>MDBs</strong> can receive messages from any enterprise information system (EIS), such as PeopleSoft or Oracle Manufacturing, not just message-oriented middleware (MOM) that supports <strong>JMS</strong>.</p>
<p>Suppose you have a legacy application that needs to send messages to an <strong>MDB</strong>. You can do this by implementing a JCA-compliant adapter/connector that includes support for message inflow contract. Once your <strong>JCA</strong> resource adapter or connector is deployed to a Java EE container, you can use the message inflow contract to have an asynchronous message delivered to an endpoint inside the container. A JCA endpoint is essentially the same as a JMS destination —it acts as a server proxy to an <strong>MDB</strong> (a message consumer/listener in JMS terms). As soon as a message arrives at the end point, the container triggers any registered <strong>MDBs</strong> listening to the endpoint and delivers the message to it.</p>
<p>For its part, the <strong>MDB</strong> implements a listener interface that is appropriate to the <strong>JCA</strong> connector/message type and passes activation configuration parameters to the <strong>JCA</strong> connector and registers as a listener to the <strong>JCA connector</strong>. <strong>JCA</strong> also enables MOM providers to integrate with Java EE containers in a standardized manner using a JCA-compliant connector or resource adapter.</p>
<p>For more information on <strong>JCA</strong>, visit <a href="http://java.sun.com/j2ee/connector/">http://java.sun.com/j2ee/connector/</a></p>
<h2>When to use Messaging and MDBs</h2>
<p>Messaging and message-driven beans are powerful concepts but they are not right for every use-case. As a rule of thumb, you should use MDBs only if you require asynchronous processing, loose-coupling, and reliability. The and part in the previous sentence is very important. Unless you need all three of these characteristics, you probably don’t need MDB.</p>
<p>If you simply need asynchronous processing and not reliability or loose-coupling, you should opt to use the session bean @Asynchronous annotation. The @Asynchronous annotation is not loosely-coupled since you invoke the asynchronous session bean method directly from client code. It is less obvious that session bean asynchronous methods are also not reliable. If the container crashes in the middle of asynchronous processing, the session bean is simply lost. With message-driven beans, on the other hand, the <strong>JMS</strong> message is not removed from the middleware until the <strong>MDB</strong> finishes processing the message. If the <strong>MDB</strong> suddenly crashes before finishing processing, the message is simply reprocessed when the container is ready again.</p>
<p>Similarly, if all you need is loose-coupling, you should take a close look at <strong>CDI</strong> events. <strong>CDI</strong> events allow message consumers and producers to be separated through elegant type-safe object-based events. Like session bean asynchronous processing, the CDI event bus is not fault-tolerant and is also not asynchronous. Note that you can combine the @Asynchronous annotation with CDI events if you need to.</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>When you do need asynchronous processing, loose-coupling and reliability, however, MDBs are one of the best solutions around—which is why they are so popular for system integration. Let’s take a closer look at why this is the case next.</p>
<h2>Why use MDBs?</h2>
<p>Given the problems that plagued EJB 2, you might question the value of EJB 3 MDBs as opposed to using some other mechanism for consuming JMS messages. The truth is that MDBs have enjoyed a reasonable degree of success even in the darkest hours of EJB. We’ll now explain why you should take a serious look at MDBs.</p>
<h3>Multithreading</h3>
<p>Your business application may require multithreaded message consumers that can process messages concurrently and maximize message throughput. MDBs help you to avoid complexity because they handle multithreading right out of the box, without any additional code. They manage incoming messages among multiple instances of beans (in a pool) that have no special multithreading code themselves. As soon as a new message reaches the destination, an MDB instance is retrieved from the pool to handle the message, as shown in figure 1. This is popularly known as MDB pooling.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/13.jpg"><img class="aligncenter size-medium wp-image-1164" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/04/13-300x78.jpg" alt="" width="300" height="78" /></a></p>
<h3>Simplified messaging code</h3>
<p>The raw JMS code to retrieve messages mirrors the JMS code to send messages and can be pretty verbose and error prone. MDBs relieve you from coding the mechanical aspects of processing JMS messages—tasks such as retrieving connection factories or destinations, creating connections, opening sessions, creating consumers, and attaching listeners. All of these tasks are handled behind the scenes for you. In EJB 3, using sensible defaults for common circumstances eliminates most of the configuration. In the worst-case scenario, you’ll have to supply configuration information using simple annotations or through the deployment descriptor.</p>
<h3>Robust message processing</h3>
<p>Reliability is a critical hallmark of <strong>MDBs</strong>. All <strong>MDBs</strong> use transactions and message acknowledgement by default. What this means is that messages are not removed from the message server unless an MDB message listener method completes normally. If an unexpected error occurs during message processing, the transaction is marked for rollback and the message receipt is not acknowledged. Because MDBs use JTA transactions, any database changes made during message listener processing is also automatically rolled back. As a result, the un-acknowledged message can be re-processed by the MDB cleanly without your having to do any work. In case of successful message processing, database changes are committed and the message is removed from the message server in an atomic fashion.</p>
<h3>Starting message consumption</h3>
<p>To start picking up messages from the shipping request queue, someone needs to invoke the appropriate method in your code. In a production environment, it is not clear how this will be accomplished. Starting message consumption thought a user-driven manual process obviously is not desirable. In a server environment, almost every means of executing the method on server startup is highly system dependent, not to mention awkward. The same is true about stopping message processing manually. On the other hand, registered MDBs would be bootstrapped or torn down gracefully by the container when the server is started or stopped.</p>
<h2>Summary</h2>
<p>Messaging is an extremely powerful technology for the enterprise, and it helps build loosely integrated reliable systems. JMS allows you to use message-oriented middleware (MOM) from enterprise Java applications without being bound to vendor-specific APIs. Using the JMS API to build a message consumer application can be time consuming, and message-driven beans (MDBs) make using MOM in standardized manner through Java EE extremely easy and robust.</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%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/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/feed/" data-count="vertical" data-text="EJB" 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/04/working-with-message-driven-beans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to secure EJB Applications?</title>
		<link>http://www.javabeat.net/2010/10/securing-ejb-applications/</link>
		<comments>http://www.javabeat.net/2010/10/securing-ejb-applications/#comments</comments>
		<pubDate>Tue, 26 Oct 2010 01:19:14 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=512</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this article, we will see the various aspects in securing an EJB Application. Security is vital not only for an enterprise application but also for any kind of application. It is essential to identify the system or the users accessing the applications and to provide access or denial for resources within the application based [...]</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">In this article, we will see the various aspects in securing an <strong>EJB Application</strong>. Security is vital not only for an enterprise application but also for any kind of application. It is essential to identify the system or the users accessing the applications and to provide access or denial for resources within the application based on some criteria. The point is that not every user should be given the rights to access sensible data and there must be some identification mechanism to distinguish this boundary. <strong>EJB</strong> specification for security falls in Declarative and Programmatic mode, the <strong>EJB</strong> Container owns the responsibility of establishing security for enterprise beans in the former mode whereas the application developer has to embed security specific code in the enterprise bean in the latter mode.</p>
<p align="justify"><span style="text-decoration: underline;"><strong>also read:</strong></span></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/11/managing-transactions-in-ejb-3-0/">Managing transactions in EJB 3.0</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 Securing EJB Application Sample Code</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/sourcecode/2010/201010-securing-ejb-applications.zip">Securing EJB Application Sample Code</a></li>
</ul>
<h2>Security</h2>
<p align="justify">Implementing the EJB security is one of the challenging task in J2EE projects. While talking about securing <strong>EJB Application</strong>s, we essentially talk about Authentication and Authorization. Authentication involves the process of verifying the user who is accessing a system. The most common way of providing online authentication for users is to supply credentials in the form of username and password and then asking the user to provide them before accessing the system. Not every user should be give access to various parts of a a system and Authorization refers to the process of ensuring whether the authenticated user has the required privilege to access a particular area in system.</p>
<ul>
<li><a href="http://www.flipkart.com/head-first-ejb-8173665265/p/itmczzj3zfmpajgt?pid=9788173665264&amp;affid=suthukrish" target="_blank">
<p align="justify">Buy head first EJB</p>
<p></a></li>
</ul>
<p align="justify">It is worthwhile to understand the relationship between users, user groups and roles before delving into the details of EJB security. For easier maintenance of security model, the responsibilities of various users within an organization will be identified and they will segregated into various user groups. For example, one set of users in an organization will own the responsibility of carrying out admin set of tasks and they can be identified and made to fall into admin user group. Similarly users performing management oriented activities may fall in the manager user group. Let us assume that the developer wants to write an enterprise bean containing business methods representing admin and management set of functionality. He may not be aware of the users and the user groups in the target environment. So, let us say that we write business methods adminOperations() and managementOperations(), then will somehow provide an indication that the method adminOperations() can be accessible by users owning the &#8216;admin&#8217; role and the method managementOperations() can be accessible by users owning the &#8216;manager&#8217; role. The role provides an abstract representation here, and in the target environment each role has to be mapped against the user groups which already exists in the operational environment.</p>
<h2>Declarative Security</h2>
<p align="justify">In this section, we will look into the concept of <strong>Declarative Security</strong>. By specifying this form of security for an Enterprise bean, we instruct the container that we are delegating the responsibility of security to the Container. <strong>EJB</strong> allows security elements to be specified at the class level and also at the method level.</p>
<h3>Annotations</h3>
<p align="justify">The various annotations that can be used with Enterprise beans are defined in the forthcoming sections. Note that it is also possible to define the security constraints for an Enterprise bean in a deployment descriptor. If the security elements are defined both in annotations and in deployment descriptor, the one specified in deployment descriptor takes precedence.</p>
<h4>DeclareRoles annotation</h4>
<p align="justify">This annotation can be specified at the class level and this will accept the list of allowed roles that an enterprise bean expects. Note that this annotation is optional, meaning that it is not necessary to declare the list of annotations before using it.</p>
<pre class="brush: java; title: ; notranslate">
@DeclareRoles({&quot;admin&quot; &quot;super-admin&quot;})
public class ManagementBean{
}</pre>
<h4>RolesAllowed annotation</h4>
<p>This annotation can be applied at the method level which will take an array of allowed roles for the method to execute. For example, in the below snippet we have declared roles &#8216;admin&#8217; and &#8216;super-admin&#8217;, and in the delete() method we have only allowed users who belong to the role &#8216;super-admin&#8217; to perform the delete operation.</p>
<pre class="brush: java; title: ; notranslate">@DeclareRoles({&quot;admin&quot; &quot;super-admin&quot;})
public class ManagementBean{

	@RolesAllowed({&quot;super-admin&quot;})
	public void delete(){
	}
}</pre>
<h4>PermitAll annotation</h4>
<p align="justify">This annotation can be applied at the class level or at the method level. This instructs the container that a user belonging to any role is allowed to access the operation. When applied at the class level, this annotation will propagate to all the business methods in the enterprise bean.</p>
<pre class="brush: java; title: ; notranslate">@DeclareRoles({&quot;admin&quot; &quot;super-admin&quot;})
public class ManagementBean{

	@RolesAllowed({&quot;super-admin&quot;})
	public void delete(){
	}

	@PermitAll
	public void viewOperation(){
	}
}</pre>
<p align="justify">For example, in the above code, we have annotated the method &#8216;viewOperation&#8217; with the <em>@PermitAll</em> annotation. This ensures that this method can be accessible by any user.</p>
<h4>DenyAll annotation</h4>
<p align="justify">This annotation can be applied both at the class and the method level. When applied at the class level, all the business methods within the enterprise bean cannot be accessible at all.</p>
<pre class="brush: java; title: ; notranslate">@DeclareRoles({&quot;admin&quot; &quot;super-admin&quot;})
public class ManagementBean{

	@RolesAllowed({&quot;super-admin&quot;})
	public void delete(){
	}

	@DenyAll
	public void deleteAll(){
	}
}</pre>
<h3>Demonstration</h3>
<p align="justify">In this example, we will provide with an example illustrating the usage of <strong>declarative security in ejbs</strong>. We will take the example of task management. Tasks can be created, assigned, completed and then deleted. We will identify four distinct roles here: &#8216;admin&#8217;, &#8216;manager&#8217;, &#8216;team-lead&#8217; and &#8216;developer&#8217;. For illustration purposes, let us assume that only a manager can create a task, a team-lead can assign a created task to a developer and the developer can complete a task once it is completed. Special privileges are given to admin for deleting tasks.</p>
<h4>Task Entity Model</h4>
<p align="justify">We will define the model for Task Entity in this section. The listing for the Task Entity model is given below.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb3.security.annotations;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class TaskEntity implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String description;
    private String assignee;
    private String status;

    public String getAssignee() {
        return assignee;
    }

    public void setAssignee(String assignee) {
        this.assignee = assignee;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
		if (!(object instanceof TaskEntity)) {
			return false;
		}
		TaskEntity other = (TaskEntity) object;
		if ((this.id == null &amp;amp;&amp;amp; other.id != null) || (this.id != null &amp;amp;&amp;amp; !this.id.equals(other.id))) {
			return false;
		}
		return true;
    }

    @Override
    public String toString() {
        return &quot;net.javabeat.articles.ejb3.security.annotations.TaskEntity[id=&quot; + id + &quot;]&quot;;
    }

}</pre>
<p>Note that the above class is modeled as an Entity bean so that the task&#8217;s information can be persisted in the database. The task has properties such as task id, name, description, assignee and status. <span style="text-decoration: underline;"><strong>Note that we have used JPA annotations to instruct that above class is an Entity class.</strong></span></p>
<h4>Task Entity Remote interface</h4>
<p align="justify">We will introduce the remote interface for the Task Entity in this section, the code for the same is given below.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb3.security.annotations;

import java.util.List;
import javax.ejb.Remote;

@Remote
public interface TaskEntityFacadeRemote {

    void createTask(String name, String description);

    void assignTask(Long taskId, String assignee);

    void completeTask(Long taskId);

    List getAllTasks();

    void deleteAllTasks();

    void create(TaskEntity taskEntity);

    void edit(TaskEntity taskEntity);

    void remove(TaskEntity taskEntity);

    TaskEntity find(Object id);

    List findAll();

}</pre>
<p align="justify">Other than the regular CRUD operations that can be applicable to any entity, this interface provides services for creating task, assigning task, completing task, listing all the tasks and deleting tasks.</p>
<h4>Task Entity Remote Implementation</h4>
<p align="justify">The implementation for the above remote interface is given below. Note that the below implementation takes new support such as dependency injection and annotations. The implementation class declares the list of roles through the annotation <em>@DelcareRoles</em> at the class level. The entity manager entity will be injected by the <strong>EJB Container</strong> with the help of annotation <em>@PersistenceContext</em>.</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.ejb3.security.annotations;

import java.util.List;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@DeclareRoles(value={&quot;admin&quot;, &quot;manager&quot;, &quot;team-lead&quot;, &quot;developer&quot;})
public class TaskEntityFacade implements TaskEntityFacadeRemote {

    @PersistenceContext
    private EntityManager em;

    @RolesAllowed(&quot;manager&quot;)
    public void createTask(String name, String description) {

        TaskEntity newTaskEntity = new TaskEntity();
        newTaskEntity.setName(name);
        newTaskEntity.setDescription(description);
        newTaskEntity.setStatus(&quot;NEW&quot;);

        em.persist(newTaskEntity);
    }

    @RolesAllowed(&quot;team-lead&quot;)
    public void assignTask(Long taskId, String assignee){

        TaskEntity taskEntity = find(taskId);
        taskEntity.setAssignee(assignee);
        taskEntity.setStatus(&quot;ASSIGNED&quot;);
        em.persist(taskEntity);
    }

    @RolesAllowed(&quot;developer&quot;)
    public void completeTask(Long taskId){

        TaskEntity taskEntity = find(taskId);
        taskEntity.setStatus(&quot;COMPLETED&quot;);
        em.persist(taskEntity);
    }

    @RolesAllowed(&quot;admin&quot;)
    public void deleteAllTasks(){

        List allTasks = findAll();
        if (allTasks != null){
            for (TaskEntity aTask : allTasks){
                remove(aTask);
            }
        }
    }

    @PermitAll
    public List getAllTasks() {
        return em.createQuery(&quot;select object(o) from TaskEntity as o&quot;).getResultList();
    }

    public TaskEntity findByName(String name){
        return null;
    }

    public void create(TaskEntity taskEntity) {
        em.persist(taskEntity);
    }

    public void edit(TaskEntity taskEntity) {
        em.merge(taskEntity);
    }

    public void remove(TaskEntity taskEntity) {
        em.remove(em.merge(taskEntity));
    }

    public TaskEntity find(Object id) {
        return em.find(TaskEntity.class, id);
    }

    public List findAll() {
        return em.createQuery(&quot;select object(o) from TaskEntity as o&quot;).getResultList();
    }

}</pre>
<p>Since in our example case, only a manager is allowed to create a task, hence the method &#8216;createTask()&#8217; is annotated with <em>@RolesAllowed</em> with the role &#8216;manager&#8217;. The method assignTask can be executed by an user who owns the role &#8216;team-lead&#8217;. Similarly the methods completeTask() and deleteAllTasks() are assigned with &#8216;developer&#8217; and &#8216;admin&#8217; roles. The annotation <em>@PermitAll</em> is used against the method &#8216;getAllTasks()&#8217; indicating that a user belonging to any role can access this operation.</p>
<h4>Persitence configuration</h4>
<p align="justify">The persistence configuration information file for persisting the Task Entity bean 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;TaskManager-ejbPU&quot; transaction-type=&quot;JTA&quot;&gt;
    &lt;provider&gt;oracle.toplink.essentials.PersistenceProvider&lt;/provider&gt;
    &lt;jta-data-source&gt;jdbc/sample&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>
<p align="justify">Note that we are using the Oracle&#8217;s TopLink as the persistence provider although any JPA compliant provider can be used. The ddl generation policy is &#8216;drop and create&#8217; which means that before every execution the database objects will be dropped and re-created.</p>
<h4>Security configuration</h4>
<p align="justify">We will discuss the security configuration in this section. Note that in the enterprise bean we have defined only roles and not users. The Enterprise beans that will be getting deployed in the target environment will have a list of users and user groups configured. So, the roles defined in the Enterprise beans have to be mapped against the user groups in the target environment.</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE sun-ejb-jar PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Application Server 9.0 EJB 3.0//EN&quot; &quot;http://www.sun.com/software/appserver/dtds/sun-ejb-jar_3_0-0.dtd&quot;&gt;
&lt;sun-ejb-jar&gt;
  &lt;security-role-mapping&gt;
    &lt;role-name&gt;admin&lt;/role-name&gt;
    &lt;group-name&gt;admin-group&lt;/group-name&gt;
  &lt;/security-role-mapping&gt;
  &lt;security-role-mapping&gt;
    &lt;role-name&gt;team-lead&lt;/role-name&gt;
    &lt;group-name&gt;team-lead-group&lt;/group-name&gt;
  &lt;/security-role-mapping&gt;
  &lt;security-role-mapping&gt;
    &lt;role-name&gt;developer&lt;/role-name&gt;
    &lt;group-name&gt;developer-group&lt;/group-name&gt;
  &lt;/security-role-mapping&gt;
  &lt;security-role-mapping&gt;
    &lt;role-name&gt;manager&lt;/role-name&gt;
    &lt;group-name&gt;manager-group&lt;/group-name&gt;
  &lt;/security-role-mapping&gt;
  &lt;enterprise-beans/&gt;
&lt;/sun-ejb-jar&gt;
</pre>
<p align="justify">In the above configuration file, we have mapped the roles &#8216;admin&#8217;, &#8216;team-lead&#8217;, &#8216;developer&#8217;, &#8216;manager&#8217; to the groups &#8216;admin-group&#8217;, &#8216;team-lead-group&#8217;, &#8216;developer-group&#8217; and &#8216;manager-group&#8217; respectively. Note that creation of user and user groups will vary across application servers.</p>
<h4>Application client</h4>
<p align="justify">The application client is given below. It does the job of invoking various services defined in the enterprise beans like creating, assigning and completing tasks.</p>
<pre class="brush: java; title: ; notranslate">package taskmanager;

import java.util.List;
import javax.ejb.EJB;
import net.javabeat.articles.ejb3.security.annotations.TaskEntity;
import net.javabeat.articles.ejb3.security.annotations.TaskEntityFacadeRemote;

public class Main {

    @EJB
    private static TaskEntityFacadeRemote taskEntityFacade;

    public static void main(String[] args) {

//        deleteAllTasks();

//        createTasks();
        Long taskIds[] = viewAllTasks();
//
//        assignTasks(taskIds, &quot;abc&quot;);
//        viewAllTasks();
//
//        completeTasks(taskIds);
//        viewAllTasks();
    }

    private static void deleteAllTasks(){

        taskEntityFacade.deleteAllTasks();
    }

    private static void createTasks(){

        taskEntityFacade.createTask(&quot;Create new feature&quot;, &quot;To create a new feature for some project&quot;);
        taskEntityFacade.createTask(&quot;To fix performance issue&quot;, &quot;To fix performance issue&quot;);
    }

    private static Long[] viewAllTasks(){

        Long[] taskIds = new Long[2];

        System.out.println(&quot;View All Tasks&quot;);
        List allTasks = taskEntityFacade.getAllTasks();
        for (int index = 0; index &amp;lt; allTasks.size(); index ++){

            TaskEntity aTaskEntity = allTasks.get(index);

            String str = aTaskEntity.getId() + &quot;,&quot;;
            str = aTaskEntity.getName() + &quot;,&quot;;
            str = str + aTaskEntity.getDescription() + &quot;,&quot;;
            str = str + aTaskEntity.getStatus() + &quot;,&quot;;

            taskIds[index] = aTaskEntity.getId();
            System.out.println(str);
        }
        return taskIds;
    }

    private static void assignTasks(Long[] taskIds, String assignee){

        for (int index = 0; index &amp;lt; taskIds.length; index ++){

            Long taskId = taskIds[index];
            System.out.println(&quot;Task Id is &quot; + taskId);
            taskEntityFacade.assignTask(taskId, assignee);
        }
    }

    private static void completeTasks(Long[] taskIds){

        for (int index = 0; index &amp;lt; taskIds.length; index ++){

            Long taskId = taskIds[index];
            taskEntityFacade.completeTask(taskId);
        }
    }
}</pre>
<p align="justify">Note that when invoking an EJB method that is secured, a dialog box will be shown prompting for username and password. The username and the password will be compared with the users that are already configured in the application server.</p>
<h2>Programmatic Security</h2>
<p align="justify">In most of the situations, it is sufficient for applications to take the advantage of declarative security services provided by the container. However, in certain other situations, this may not be the case. For example, let us assume the scenario of a registered user downloading files from a portal. The download operation has to check whether the user belongs to the group of registered users for which case the declarative security case is sufficient. Now, let us assume that we want to prevent the user from downloading resource that has exceeded the maximum limit of ten. Now we run into a dynamic condition and based on that we allow or deny a particular operation to the user. This is where the programmatic security comes into picture.</p>
<h3>Demonstration</h3>
<p align="justify">We will take the example of user trying to perform various operations on a blog for illustrating programmatic security. Considering the operations – replying to a post in the blog and downloading files from the blog. A user is allowed to reply to a post only when he is a registered user and the number of posts created by the user is more than 10. Similarly for the download operation, other then being a registered user, the user has to be a premium user to perform the download operation.</p>
<h4>User Entity</h4>
<p align="justify">The user entity model is given below. Note that we have made use of JPA annotations to indicate that this model is a JPA entity.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb3.security.programatic;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity(name=&quot;User&quot;)
@Table(name = &quot;T_USER&quot;)
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String userId;
    private boolean isPremiumUser;
    private int postsCount;

    public boolean getIsPremiumUser() {
        return isPremiumUser;
    }

    public void setIsPremiumUser(boolean isPremiumUser) {
        this.isPremiumUser = isPremiumUser;
    }

    public int getPostsCount() {
        return postsCount;
    }

    public void setPostsCount(int postsCount) {
        this.postsCount = postsCount;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof User)) {
            return false;
        }
        User other = (User) object;
        if ((this.id == null &amp;amp;&amp;amp; other.id != null) || (this.id != null &amp;amp;&amp;amp; !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return &quot;net.javabeat.articles.ejb3.security.programatic.User[id=&quot; + id + &quot;]&quot;;
    }

}</pre>
<p align="justify">We have declared &#8216;userId&#8217;, &#8216;isPremiumUser&#8217; and &#8216;postsCount&#8217; as the properties for the User Entity.</p>
<h4>User Remote Interface</h4>
<p align="justify">The remote user interface for performing various operations such as replying to a posting and downloading resources from a blog is given below.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb3.security.programatic;

import java.util.List;
import javax.ejb.Remote;

@Remote
public interface UserFacadeRemote {

    void deleteAllUsers();

    void create(User user);

    void create(String userId, boolean premiumUser, int postsCount);

    void downloadAttachment(Long userId);

    void edit(User user);

    void remove(User user);

    User find(Object id);

    List findAll();

    void replyPost(Long userId, String comment);
}</pre>
<p align="justify">Note that other than the service methods for creating users, replying to a post and downloading resources, it contains the regular functionalities for performing CRUD operations. Note that we are not going to provide real-time implementations for the service methods.</p>
<h4>User Interface Implementation</h4>
<p align="justify">The implementation class for the above remote interface is given below. Note that the declared role for this class is &#8216;registered_role&#8217;. Note that through dependency injection, we have injected the objects <strong>EntityManager and SessionContext</strong>. In the replyPost() method, other than checking whether the user invoking the method belongs to the desired role, additional check is performed for the number of created posts.</p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.ejb3.security.programatic;

import java.security.Principal;
import java.util.List;
import javax.annotation.Resource;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@DeclareRoles({&quot;registered_role&quot;})
public class UserFacade implements UserFacadeRemote {

    @PersistenceContext
    private EntityManager em;

    @Resource
    private SessionContext context;

    public void deleteAllUsers(){

        List allUsers = findAll();
        if (allUsers != null){
            for (User user : allUsers){
                remove(user);
            }
        }
    }

    public void create(String userId, boolean premiumUser, int postsCount) {

        User newUser = new User();
        newUser.setIsPremiumUser(premiumUser);
        newUser.setPostsCount(postsCount);
        newUser.setUserId(userId);

        em.persist(newUser);
    }

    public void create(User user) {
        em.persist(user);
    }

    public void edit(User user) {
        em.merge(user);
    }

    public void remove(User user) {
        em.remove(em.merge(user));
    }

    public User find(Object id) {
        return em.find(User.class, id);
    }

    public List findAll() {
        return em.createQuery(&quot;select object(o) from User as o&quot;).getResultList();
    }

    @RolesAllowed(&quot;registered_role&quot;)
    public void replyPost(Long userId, String comment){

        Principal principal = context.getCallerPrincipal();
        System.out.println(&quot;Name &quot; + principal.getName());
        if (context.isCallerInRole(&quot;registered_role&quot;)){

            User userObject = find(userId);
            if (!(userObject.getPostsCount() &amp;gt; 10)){
                throw new SecurityException(&quot;Post creation not allowed&quot;);
            }else{
                // All creating posts
            }
        }
    }

    @RolesAllowed(&quot;registered_role&quot;)
    public void downloadAttachment(Long userId){

        Principal principal = context.getCallerPrincipal();
        System.out.println(&quot;Name &quot; + principal.getName());
        if (context.isCallerInRole(&quot;registered_role&quot;)){

            User userObject = find(userId);
            if (!(userObject.getIsPremiumUser())){
                throw new SecurityException(&quot;Downloading allowed only for premium users&quot;);
            }else{
                // Allow to download the attachment
            }
        }
    }
}</pre>
<p align="justify">For the downloadAttachment() operation, we are checking if the invoking user is a registered user and if the user is a premium user. We are making use of the Context object here to find out if the invoking user is in the desired role through the &#8216;isCallerInRole()&#8217; method. Other methods of interest in the Context object with respect to the Security is the getCallerPrincipal() method which provides an encapsulatation of the user credentails that is created in the <strong>EJB container</strong>.</p>
<h2>Conclusion</h2>
<p align="justify">This article started with explaining the various security aspects supported by <strong>EJB Security</strong>. It then explained the declarative security model with the list of annotations supported, which was then followed by a demonstration. Since declarative security model may not be flexible and suitable in all scenarios, programmatic mode of <strong>security</strong> is also explained with the help of an example.</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/11/managing-transactions-in-ejb-3-0/">Managing transactions in EJB 3.0</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/10/securing-ejb-applications/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>EJB Interview Questions</title>
		<link>http://www.javabeat.net/2009/02/ejb-interview-questions/</link>
		<comments>http://www.javabeat.net/2009/02/ejb-interview-questions/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 15:32:29 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB]]></category>
		<category><![CDATA[Interview Questions]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=389</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>1. What is EJB? EJB stands for Enterprise JavaBeans and is widely-adopted server side component architecture for J2EE. It enables rapid development of ission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in. 2. What is session Facade? Session Facade is a design pattern to access the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1. What is EJB?</h2>
<p>EJB stands for Enterprise JavaBeans and is widely-adopted server side component architecture for J2EE. It enables rapid development of ission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in.</p>
<h2>2. What is session Facade?</h2>
<p>Session Facade is a design pattern to access the Entity bean through local interface than accessing directly. It increases the performance over the network. In this case we call session bean which on turn call entity bean.</p>
<h2>3. What is EJB role in J2EE?</h2>
<p>EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform.</p>
<h2>4. What is the difference between EJB and Java beans?</h2>
<p>EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.</p>
<h2>5. What are the key features of the EJB technology?</h2>
<ol>
<li>EJB components are server-side components written entirely in the Java programming language</li>
<li>EJB components contain business logic only &#8211; no system-level programming &amp; services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server.</li>
<li>EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.</li>
<li>EJB components are fully portable across any EJB server and any OS.</li>
<li>EJB architecture is wire-protocol neutral&#8211;any protocol can be utilized like IIOP, JRMP, HTTP, DCOM, etc.</li>
</ol>
<h2>6. What are the key benefits of the EJB technology?</h2>
<ol>
<li>Rapid application development</li>
<li>Broad industry adoption</li>
<li>Application portability</li>
<li>Protection of IT investment</li>
</ol>
<h2>7. How many enterprise beans?</h2>
<p>There are three kinds of enterprise beans:</p>
<ol>
<li>session beans,</li>
<li>entity beans, and</li>
<li>message-driven beans.</li>
</ol>
<h2>8. What is message-driven bean?</h2>
<p>A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier.</p>
<h2>9. What are Entity Bean and Session Bean?</h2>
<p>Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence (CMP) and Bean-Managed Persistence (BMP).</p>
<p>Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn&#8217;t maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations.</p>
<h2>10. How EJB Invocation happens?</h2>
<p>Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean).</p>
<h2>11. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?</h2>
<p>You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be considering as passed-by-value that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container. The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.</p>
<h2>12. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes?</h2>
<p>The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. While referring the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer.</p>
<h2>13. Can the primary key in the entity bean be a Java primitive type such as int?</h2>
<p>The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive).</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>14. Can you control when passivation occurs?</h2>
<p>The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA Weblogic, provide the ability to tune the container to minimize passivation calls. Taken from the Weblogic 6.0 DTD -The passivation-strategy can be either default or transaction. With the default setting the container will attempt to keep a working set of beans in the cache. With the transaction setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).</p>
<h2>15. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other?</h2>
<p>Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Managed. In Container Managed Entity Bean &#8211; Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistence storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean &#8211; The developer has to specifically make connection, retrieve values, assign them to the objects in the ejbLoad() which will be called by the container when it instantiates a bean object. Similarly in the ejbStore() the container saves the object values back the persistence storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you don’t need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container.</p>
<h2>16. What is EJB QL?</h2>
<p>EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistence and is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.</p>
<h2>17. Brief description about local interfaces?</h2>
<p>EEJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.</p>
<h2>18. What are the special design cares that must be taken when you work with local interfaces?</h2>
<p>It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.</p>
<h2>19. What happens if remove( ) is never invoked on a session bean?</h2>
<p>In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of Stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.</p>
<h2>20. What is the difference between Message Driven Beans and Stateless Session beans?</h2>
<p>In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.</p>
<h2>21. How can I call one EJB from inside of another EJB?</h2>
<p>EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.</p>
<h2>22. What is an EJB Context?</h2>
<p>EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.</p>
<h2>23. Is it possible for an EJB client to marshal an object of class java.lang.Class to an EJB?</h2>
<p>Technically yes, spec. compliant NO! &#8211; The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.</p>
<h2>24. Is it legal to have static initializer blocks in EJB?</h2>
<p>Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields &#8211; which may be illegal in EJB if they are read/write &#8211; In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.</p>
<h2>25. Is it possible to stop the execution of a method before completion in a SessionBean?</h2>
<p>Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB.</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/ejb-interview-questions/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>What is Web Beans?</title>
		<link>http://www.javabeat.net/2008/12/what-is-web-beans/</link>
		<comments>http://www.javabeat.net/2008/12/what-is-web-beans/#comments</comments>
		<pubDate>Wed, 31 Dec 2008 13:16:49 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB]]></category>
		<category><![CDATA[WebBeans]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=217</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>1.Introduction This article introduces new unified framework for the Java EE environment, called Web Beans.This article is written based on the specification available at the time of writing this article. The specification for this framework is still under the public review, so there may be few changes before the final release. You can read the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1.Introduction</h2>
<p>This article introduces new unified framework for the Java EE environment, called <strong><em>Web Beans</em></strong>.This article is written based on the specification available at the time of writing this article. The specification for this framework is still under the public review, so there may be few changes before the final release. You can read the <strong>JSR 299</strong> <a href="http://jcp.org/en/jsr/detail?id=299" target="_blank">here</a>. <strong>Web Beans</strong> is open source framework currently in the Alpha release. <em><a href="http://in.relation.to/Bloggers/Gavin" target="_blank">Gaving King</a></em>, who is also the founder of famous framework <strong><a href="http://www.javabeat.net/2007/06/introduction-to-jboss-seam/">JBoss Seam</a></strong> is also the specification lead for the <strong>Web Beans</strong>. There is lot of welcome notes for this framework and it solves many issues which is not addressed by the Java EE specifications. It is expected to be shipped with <strong>Java EE 6.0</strong> edition. Lets jump into the next sections to read more about the <strong>Web Beans</strong>.</p>
<h2>2.What is Web Beans?</h2>
<p>What exactly is the <strong>Web Beans</strong>?. If you want to understand the real need for <strong>Web Beans</strong>, then little recap to the Java EE evolution is needed. The problem with the Java EE edition is, the presentation layers(Servlets, JSP and JSF) and persistance layers(EJB 3.0, JTA, JCA and JPA) are grown seperatly without much closer interactions. There is no common technology to integrate the both web tier and the persistance tier. Web Beans main goal is to address this issue by defining beans which can be interacted by multiple tiers. Web Beans will be compatiable with technologies in the both tiers. Web Beans is influenced by the popular frameworks <strong><a href="http://www.javabeat.net/articles/29-introduction-to-google-guice-1.html" target="_blank">Google Guice</a></strong> and <strong><a href="http://www.javabeat.net/2007/06/introduction-to-jboss-seam/">JBoss Seam</a></strong>.</p>
<p>If the Java Bean has the constructor with no parameter, then it is a Web Beans. Almost every Java Bean you are writing in your code<br />
is a Web Beans by its nature. If you have existing applications with thousands of classes, you can make use of the Web Beans specification without touching the code. This can be done by the XML configuration for all the beans.</p>
<p>The following are the few points to consider while writing the Web Beans:</p>
<ul>
<li>To qualify as the valid Web Beans implementation, the beans must have no argument constructor. Web Beans manager calls this constructor for the initialization purpose. It is called once when the web Beans instance is created.</li>
<li><strong>Web Beans</strong> can be implemented without no argument constructor, If it defines constructor with <em>@Initializer</em> annotation or any of the method with the <em>@Initializer</em> annotation. The methods or constructors with <em>@Initializer</em> will be called while bean instance is created.</li>
<li>Web Beans must be annotated with @Component. This annotation helps Web Beans manager to identify all the Web Beans in the classpath. Web Beans manager scans the classpath and load all the beans annotated with @Component.</li>
<li>From the Web Beans specification <em>&#8220;A Web Bean implementation may be a Java class, an EJB session or singleton bean class, a producer method or a JMS queue or topic,&#8221;</em></li>
<li>@Initializer must be used exactly for the one constructor or one method in the class. Otherwise, DefinitionException is thrown by the Web Beans manager.</li>
</ul>
<p><strong>EJB 3.0</strong> has simplified the <em>EJB programming model</em> and heavy use of <em>annotations</em>. But, even though <strong>EJB 3.0</strong> has lot of gaps which is not addressed by the EJB 3.0 specification. One of the main problem with the EJBs are, still it cannot be used directly in the presentation layer. In the existing <strong>EJB 3.0</strong> specification, it doesn&#8217;t provide any facilities to use EJB&#8217;s as the <strong>JSF</strong> backing beans. This gap is not filled by any of the existing technologies in the Java EE edition. The main goal of the web Beans is to enable <strong>JSF</strong> using the <strong>EJB 3.0</strong> as the managed beans. In one word, it simplifies the interaction between application layer and the presentation layer. Unifying the two component models and enabling a considerable simplification to the programming model for web-based applications in Java. This will help the rapid application developement. Web Beans specification will be more generalized to use by any technologies in future other than EJB 3.0 and JSF.</p>
<h2>3.Web Beans Constructor</h2>
<h3>3.1.declaration using @Initializer</h3>
<p>Web Bean manager calls the Web Beans constructor to create the instance. The constructors for the Web Bean can be defined using<br />
the @Initializer annotation. The same declaration as follows:</p>
<pre class="brush: java; title: ; notranslate">@RequestScoped
public class WebBeansSample{
	@Initializer
	public WebBeansSample(){

	}
}</pre>
<p>In the above code, WebBeansSample is a simple Web Bean and its WebBeansSample() constructor will be invoked while creating the instance. <strong><em>@RequestScoped</em></strong> annotation specifies that the bean is visible to the other beans in the request scope. If there is only constructor in the class with no arguments, then it is not necessary to use the <strong><em>@Initializer annotation</em></strong>. <strong><em>@Initializer</em></strong> is mandatory only when if there is constructors with arguments that has to be used for the initialization purposes. Note that <strong><em>@Initializer</em></strong> can be used exactly one place in the class. That must be constructor or a method.</p>
<p>The following code will throw DefinitionException by the Web Bean manager:</p>
<pre class="brush: java; title: ; notranslate">@RequestScoped
public class WebBeansSample{
	@Initializer
	public WebBeansSample(){

	}
	@Initializer
	public WebBeansSample(InjectObject obj){

	}
}</pre>
<p>the above code is not valid since <em>@Initializer</em> is used two times.</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>
<h3>3.2.declaration using XML</h3>
<p>The Web Beans constructors can be declared using the XML file. Web Beans are declared in the web-beans.xml file. The constructors<br />
definition can be written inside the bean element. Look into the following example:</p>
<pre class="brush: java; title: ; notranslate">
&lt;myapp:WebBeansSample&gt;
    &lt;RequestScoped/&gt;
    &lt;myapp:InjectObject/&gt;
&lt;/myapp:WebBeansSample&gt;
</pre>
<p>In the above code, <em>myapp:InjectObject</em> tells the Web Bean manager about the constructor. If the constructor definition is missing in the XML file, then it looks for the default no argument constructor in the class. When the constructor has parameters, Web Bean manager calls the method Manager.getInstanceByType() to get the value for the parameters.</p>
<h2>5.Web Beans Lifecycle</h2>
<p><strong>Web Beans lifecycle</strong> depends upon the type nature of the Web Beans. <em>Web Beans</em> can be anything like <em>EJBs</em>, <em>JMS end points</em> or Simple Java Beans. So the lifecycle also will be different for the different type of web beans. Creating and destruction is the common <em>lifecylcle</em> events for all types of web beans. But, the two events behave differenetly for the different type of beans. In the next section we will look into the Creation and Destruction of the web beans.</p>
<h3>5.1.Web Beans Creation</h3>
<p>The <em>create()</em> is called when Web Beans instance is created. This method is responsible for completing the certain tasks<br />
before the instance is created. The following are list of tasks to be performed:</p>
<ul>
<li>Getting the instance for the Web Bean</li>
<li>Creating interceptors and decorator objects and binding to the web bean instance.</li>
<li>Injects all the dependencies</li>
<li>Setting the initial values defined in <strong>XML</strong> file for the Web Bean.</li>
<li>Calls the <strong>@PostConstruct</strong> method if it is required.</li>
</ul>
<p>If there is any exception thrown while creating the instance, it will be rethrown by the <em>create()</em> method as the <em>CreateException</em> only if it is checked exception.</p>
<h3>5.2.Web Beans Destruction</h3>
<p>The <em>destroy()</em> method is responsible for destroying the web beans. The following are the tasks performed by the <em>destroy()</em><br />
method:</p>
<ul>
<li>Calls the Web Bean remove method or disposal method</li>
<li>Calls the <strong>@PreDestroy</strong> method, if required</li>
<li>Destroys all dependent objects of the instance. Web Bean manager is allowed to destroy <em>@Dependent</em> scoped beans at any time.</li>
</ul>
<h2>Summary</h2>
<p>In this article you have learnt about the basic concepts behind the <strong><em>Web Beans</em></strong> specification and the main goal of the framework. Also we have explained you about the constructors and <strong>lifecycle</strong> for the <strong>Web Beans</strong>. This article doesn&#8217;t explain you about writing the example program for <strong>Web Beans</strong>. We will be publishing series of articles on the <strong>Web Beans</strong>. So, please wait we will be coming with another article on web Beans soon.</p>
<h2>Web Beans Reference</h2>
<ul>
<li><a href="http://jcp.org/en/jsr/detail?id=299" target="_blank">JSR 299</a></li>
<li><a href="http://docs.jboss.org/webbeans/reference/1.0.0.ALPHA1/en/html/" target="_blank">Web Beans Reference Guide</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/2008/12/what-is-web-beans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EJB Webservices in JBoss application server sample code</title>
		<link>http://www.javabeat.net/2008/09/ejb-webservices-in-jboss-application-server-sample-code/</link>
		<comments>http://www.javabeat.net/2008/09/ejb-webservices-in-jboss-application-server-sample-code/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 00:52:37 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[EJB]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[WebService]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=354</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>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 Employee Service.java ---------------------- package [...]</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>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Employee Service.java
----------------------
package com.crm.services;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import com.crm.bean.Employee;
/**
* @author AnilKumar
*
*/
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface EmployeeService {
public Employee getEmployee(long pin);
}
&nbsp;
EmployeeServiceImpl.java
-------------------------
package com.crm.services;
&nbsp;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
&nbsp;
import com.crm.bean.Employee;
import com.crm.model.EmployeeDAO;
import com.crm.modelinterface.cmsEmployee;
/**
* @author AnilKumar
*
*/
@Stateless
@WebService(endpointInterface = &quot;com.crm.services.EmployeeService&quot;)
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class EmployeeServiceImpl {
&nbsp;
@WebMethod(operationName = &quot;getEmployee&quot;)
public Employee getEmployee(@WebParam(name = &quot;pin&quot;)
long pin) {
cmsEmployee employee2 = new EmployeeDAO();
// Employee employee2 = employeeDAO.getEmployeebyemployee(pin);
&nbsp;
Employee employee = employee2.getEmployeebyemployee(pin);
&nbsp;
System.out.println(employee.getFirstname());
return employee;
}
&nbsp;
}</pre></td></tr></table></div>

<p>deploy above two classes by archieving in a jar and copy it to deploy folder of jboss<br />
then run ur jboss server with url http://localhost:8080/jbossws there u will get all ur<br />
web services running in your server. the client program will be like this</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>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package com.crm.serviceClient;
&nbsp;
import java.net.MalformedURLException;
import java.net.URL;
&nbsp;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
&nbsp;
import com.crm.bean.Employee;
import com.crm.services.EmployeeService;
/**
* @author AnilKumar
*
*/
@WebServiceClient(name = &quot;EmployeeServiceImplService&quot;, targetNamespace = &quot;http://services.crm.com/&quot;,
wsdlLocation = &quot;http://localhost:8080/jarfilename/EmployeeServiceImpl?wsdl&quot;)
public class EmployeeServiceClient extends Service {
protected EmployeeServiceClient(URL wsdlDocumentLocation,
QName serviceName) {
super(wsdlDocumentLocation, serviceName);
// TODO Auto-generated constructor stub
}
&nbsp;
public EmployeeServiceClient() throws MalformedURLException {
super(new URL(
&quot;http://localhost:8080/jarfilename/EmployeeServiceImpl?wsdl&quot;),
new QName(&quot;http://services.crm.com/&quot;,
&quot;EmployeeServiceImplService&quot;));
}
&nbsp;
@WebEndpoint
public EmployeeService getEmployeeServiceport() {
return (EmployeeService) super.getPort(new QName(
&quot;http://services.crm.com/&quot;, &quot;EmployeeServiceImplPort&quot;),
EmployeeService.class);
&nbsp;
}
&nbsp;
public static void main(String[] args) throws MalformedURLException {
&nbsp;
try {
EmployeeService service = new EmployeeServiceClient().getEmployeeServiceport();
&nbsp;
if (service != null) {
System.out.println(&quot;Serrvice not null&quot;);
Employee employee1 = service.getEmployee(18);
&nbsp;
System.out.println(employee1.getFirstname());
System.out.println(employee1.getLastname());
}
&nbsp;
} catch (Exception e) {
e.printStackTrace();
}
&nbsp;
}
&nbsp;
}</pre></td></tr></table></div>

<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/09/ejb-webservices-in-jboss-application-server-sample-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create EJB 3.0 project in NetBeans 6.1</title>
		<link>http://www.javabeat.net/2008/07/create-ejb-3-0-project-in-netbeans-6-1/</link>
		<comments>http://www.javabeat.net/2008/07/create-ejb-3-0-project-in-netbeans-6-1/#comments</comments>
		<pubDate>Fri, 04 Jul 2008 10:17:47 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[NetBeans]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=112</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 This article explains how to create EJB 3.0 project using NetBeans IDE 6.1. This article will not explain the details of EJB 3.0 but will give basic knowledge on how to create simple EJB 3.0 project using NetBeans 6.1 IDE. Creating Project in NetBeans 6.1 Step 1 : Create Project Show Full Image Step [...]</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>This article explains how to create EJB 3.0 project using NetBeans IDE 6.1. This article will not explain the<br />
details of EJB 3.0 but will give basic knowledge on how to create simple EJB 3.0 project using NetBeans 6.1 IDE.</p>
<h2>Creating Project in NetBeans 6.1</h2>
<h3>Step 1 : Create Project</h3>
<p><img src="images/2008/07/1.gif" alt="" width="500" /></p>
<p><a href="articleImageOpen('images/2008/07/1.gif');">Show Full Image</a></p>
<h3>Step 2 : Select Enterprice Project</h3>
<p><img src="images/2008/07/2.gif" alt="" width="500" /></p>
<p><a href="articleImageOpen('images/2008/07/2.gif');">Show Full Image</a></p>
<h3>Step 3 : Specify Project Name</h3>
<p><img src="images/2008/07/3.gif" alt="" width="500" /></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><a href="articleImageOpen('images/2008/07/3.gif');">Show Full Image</a></p>
<h3>Step 4 : Select server and create EJB,WEb modules</h3>
<p><img src="images/2008/07/4.gif" alt="" width="500" /></p>
<p><a href="articleImageOpen('images/2008/07/4.gif');">Show Full Image</a></p>
<h3>Step 5 : Project is created</h3>
<p><img src="images/2008/07/5.gif" alt="" width="500" /></p>
<p><a href="articleImageOpen('images/2008/07/5.gif');">Show Full Image</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/07/create-ejb-3-0-project-in-netbeans-6-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Beans in EJB(BMP)</title>
		<link>http://www.javabeat.net/2008/05/entity-beans-in-ejbbmp/</link>
		<comments>http://www.javabeat.net/2008/05/entity-beans-in-ejbbmp/#comments</comments>
		<pubDate>Sun, 25 May 2008 00:43:57 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[EJB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=334</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>ENTITY BEAN WITHBEAN-MANAGED PERSISTENCE ========================================== Thus far, we acquainted ourselves with Sessionbeans ( both stateless &#38; stateful) and also CMP Entity bean. In this instalment, we take up the most difficult type, (ie) Bean-Managed Persistent Entity bean.(BMP) &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212; Example for Bean-Managed Entity Bean ==================================== We have to write the SQL code for Persistence ,ourselves, in [...]</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><b><span><span></span>ENTITY BEAN WITH<span></span>BEAN-MANAGED<br />
PERSISTENCE </span></b></p>
<p class="MsoNormal"><b><span><span></span>==========================================</span></b><span></span></p>
<p class="MsoNormal"><span>Thus far, we acquainted ourselves with <b>Sessionbeans</b><br />
( both stateless &amp; stateful) and also <b>CMP Entity bean</b>.</span></p>
<p class="MsoNormal"><span>In this instalment, we take up the most<br />
difficult type, (ie) <b>Bean-Managed Persistent Entity bean.(BMP)</b></span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span>Example for<b> Bean-Managed Entity Bean</b></span></p>
<p class="MsoNormal"><span>====================================</span></p>
<p class="MsoNormal"><span><span></span>We have to write the SQL code for Persistence ,ourselves, in the case of<br />
Bean-Managed persistence. In our example,If we consider a single instance of<br />
the bean, it exists as an object in <b>memory</b> with 3 <b>attributes</b><br />
(key,name,place)<span></span>At the same time, it<br />
should also be persisted as a <b>row</b>, with corresponding <b>fields</b>,<br />
in<span></span>&#039;<b>table1&#039; </b>of &#039;customer&#039;<b><br />
database </b>in hard disk.They should match. This is known as <b>&#039;Synchronization&#039;</b>.</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>The mechanism by which Synchronization is achieved by various vendors<br />
may vary. It is known as <b>&#039;Object-relational mapping&#039;</b>.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>Whether, it is CMP<span></span>or BMP, the<br />
process of synchronising is done by the <b>container</b>.The only difference is<br />
that , in CMP , we do not write any <b><span></span>SQL </b>for Storing ( memory to hard disk)or<br />
for &#039;Loading&#039; (hard disk to memory).In BMP, we have to write the <b>SQL</b> for<br />
these<span></span>tasks.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>However, the client cannot explicitly , call either &#039;load&#039; or &#039;store&#039;<br />
functions. This job is taken care of by the Container.Depending on a number of<br />
factors<span></span>such as <b>Transaction<br />
monitoring</b>, the container chooses the appropriate moment to synchronize the<br />
data in memory with the data in table of hard disk storage.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>This process, is <b>transparent</b> ,(ie) the programmer need not know<br />
about it. The methods are <b>&#039;callback&#039; </b>methods. Such methods are called by<br />
the container by itself without explicit user program or interaction.</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></p>
<p class="MsoNormal"><span><span></span>In<br />
CMP, we just deal with the objects in memory. The task of persistence is<br />
automatically done by the container, at the appropriate time. The container<br />
itself generates the required SQL code to perform this task. But, in BMP , we<br />
should write the necessary SQL code for Store and Load.</span></p>
<p class="MsoNormal"><span>This is the difference between CMP and BMP.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&#8212;&#8211;</span></p>
<p class="MsoNormal"><span><span></span>Which is better? Opinions differ.One camp claims that CMP is better<br />
because,it abstracts the details about the underlying database and deals only<br />
with objects in memory.</span></p>
<p class="MsoNormal"><span><span></span>The other camp feels that CMP is useful only for very simple cases and<br />
most of the real life applications are complex, requiring joins from different<br />
tables and CMP is not suitable for real life situations.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>It<br />
will be safer for us to be conversant with BMP , in case it is needed by our<br />
application.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&#8212;&#8212;</span></p>
<p class="MsoNormal"><span><span></span>As<br />
before ( as in the case of CMP), we begin with :</span></p>
<p class="MsoNormal"><span><span></span>i)<span></span>customerRemote.java</span></p>
<p class="MsoNormal"><span><span></span>ii) customerHome.java</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span>A<span></span>DEMO FOR BEAN-MANAGED PERSISTENT ENTITY-BEAN</span></b></p>
<p class="MsoNormal"><span>================================================</span></p>
<p class="MsoNormal"><span><span></span>Access Database name : Customer</span></p>
<p class="MsoNormal"><span><span></span>table<span></span>name<span></span>:<span></span>table1</span></p>
<p class="MsoNormal"><span><span></span>Three fields ( key, name, place) ( all String type).</span></p>
<p class="MsoNormal"><span><span></span>(Primary key field is &#039;key&#039;).</span></p>
<p class="MsoNormal"><span><span></span>For our example, remember to register the database &#039;customer&#039;</span></p>
<p class="MsoNormal"><span><span></span>with ODBC.</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span>( The java source files for<br />
&#039;customerRemote&#039; &amp;</span></p>
<p class="MsoNormal"><span><span></span>&#039;customerHome&#039;<span></span>are the same as<br />
for CMP bean.</span></p>
<p class="MsoNormal"><span>====================================================</span></p>
<p class="MsoNormal"><span>Let us create our source files in the<br />
following folder:</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span>c:weblogicbeansbmpdemo</span></b></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></p>
<p class="MsoNormal"><span>As before remember to set JAVA_HOME,<br />
WL_HOME.</span></p>
<p class="MsoNormal"><span><span></span>Also, set path &amp; classpath;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>c:weblogicbeans<b>bmpdemo&gt;</b>set<br />
JAVA_HOME=C:JDK1.3</span></p>
<p class="MsoNormal"><span><span></span><b>&#8230;bmpdemo&gt;</b>set<br />
WL_HOME=C:WEBLOGIC</span></p>
<p class="MsoNormal"><span><span></span>&#8230;<b>bmpdemo&gt;</b>set<br />
path=c:windowscommand;</span></p>
<p class="MsoNormal"><span><span></span>c:jdk1.3bin;</span></p>
<p class="MsoNormal"><span><span></span>c:weblogicbin</span></p>
<p class="MsoNormal"><span><span></span>&#8230;<b>bmpdemo</b>&gt;set<br />
classpath=c:weblogicbeansbmpdemo;</span></p>
<p class="MsoNormal"><span><span></span>c:weblogicclasses;</span></p>
<p class="MsoNormal"><span><span></span>c:weblogiclibweblogicaux.jar;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b>customerRemote.java</b></span></p>
<p class="MsoNormal"><b><span><span></span>====================<span></span></span></b></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>import javax.ejb.*;</span></p>
<p class="MsoNormal"><span>import java.rmi.*;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>public interface <b>customerRemote</b><br />
extends EJBObject</span></p>
<p class="MsoNormal"><span>{</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>public String<span></span>getName()<span></span>throws RemoteException;</span></p>
<p class="MsoNormal"><span><span></span>public void<span></span>setName(String<span></span>s)<span></span>throws RemoteException;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>public String<span></span>getPlace()<span></span>throws RemoteException;</span></p>
<p class="MsoNormal"><span><span></span>public<span></span>void<span></span>setPlace(String s) throws RemoteException;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>}</span></p>
<p class="MsoNormal"><span>================================================================</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>customerHome.java</b></span></p>
<p class="MsoNormal"><b><span><span></span>=================</span></b></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>import javax.ejb.*;</span></p>
<p class="MsoNormal"><span>import java.rmi.*;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>public interface <b>customerHome</b><br />
extends EJBHome</span></p>
<p class="MsoNormal"><span>{</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>public<span></span>customerRemote<span></span><b><span></span>create</b>(String a, String b, String c)<br />
throws</span></p>
<p class="MsoNormal"><span><span></span>RemoteException,<br />
CreateException;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>public customerRemote<span></span><b><span></span>findByPrimaryKey</b>(String a) throws</span></p>
<p class="MsoNormal"><span><span></span>RemoteException,<br />
FinderException;<span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>===================================================================</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>The difference between CMP and BMP occurs only in the Bean class.</span></p>
<p class="MsoNormal"><span>Therefore the Remote and Home files are<br />
exactly same for CMP and BMP.</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212; &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span>We now take up customerBean.java</span></b></p>
<p class="MsoNormal"><b><span><span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span></span></b><span><span></span>As this is a lenthy file, it is always good<br />
practice to list the sequence in which the functions appear in code file:</span></p>
<p class="MsoNormal"><span><span></span>(This is just for convenience in code-reading).</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span><span></span></span></b><span><span></span>1)<span></span>setName(</span></p>
<p class="MsoNormal"><span><span></span>2)<span></span>getName()</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>3)<span></span>setPlace(</span></p>
<p class="MsoNormal"><span><span></span>4)<span></span>getPlace()</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>5)<span></span><b>getConnection ()<span></span>( this is defined by us)</b></span></p>
<p class="MsoNormal"><b><span></span></b></p>
<p class="MsoNormal"><b><span><span></span></span></b><span><span></span>6)<span></span>ejbCreate(</span></p>
<p class="MsoNormal"><span><span></span>7)<span></span>ejbFindByPrimaryKey(</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>8)<span></span>ejbLoad()</span></p>
<p class="MsoNormal"><span><span></span>9)<span></span>ejbStore()</span></p>
<p class="MsoNormal"><span><span></span>10)<span></span>ejbRemove()</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>11)<span></span>ejbPostCreate(</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>12)<span></span>ejbSetEntityContext(</span></p>
<p class="MsoNormal"><span><span></span>13)<span></span>ejbUnsetEntityContext()<span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>14)<span></span>ejbActivate()</span></p>
<p class="MsoNormal"><span><span></span>15)<span></span>ejbPassivate() </span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>(<b>note:<span></span></b>A single round bracket means there are parameter/parameters).</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></p>
<p class="MsoNormal"><span>It will necessary to give very brief note<br />
on the purpose of these various methods.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>a)The important function is &#039;<b>getConnection</b>&#039;.<br />
This is written by us.</span></p>
<p class="MsoNormal"><span><span></span>The<span></span>purpose is to to get<br />
connection to the database.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>b) &#039;<b>ejbCreate</b>&#039; method is called when<br />
the client invokes &#039;create&#039; </span></p>
<p class="MsoNormal"><span><span></span>method. Its purpose is to create a<span></span>new object in memory with the </span></p>
<p class="MsoNormal"><span><span></span>parameters passed by the client and also create the corresponding </span></p>
<p class="MsoNormal"><span><span></span>row in the database table.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>c)<span></span><b>&#039;ejbPostCreate&#039;</b><br />
is called after &#039;ejbCreate&#039; by the container.This</span></p>
<p class="MsoNormal"><span><span></span>can be used for any desired tasks.It should have the same </span></p>
<p class="MsoNormal"><span><span></span>parameters as the &#039;ejbCreate&#039; method.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>d)<span></span><b>&#039;ejbLoad&#039;</b><br />
is meant for bringing a row from table into the memory.</span></p>
<p class="MsoNormal"><span><span></span>depending on the primary key in the current context.</span></p>
<p class="MsoNormal"><span><span></span>( <b>context.getPrimaryKey() </b>).and setting the attributes of the </span></p>
<p class="MsoNormal"><span><span></span>object accordingly. This is a &#039;callback&#039; method (ie) it is invoked </span></p>
<p class="MsoNormal"><span><span></span>at the appropriate time by the container.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>e)<span></span><b>&#039;ejbStore&#039;</b><br />
is meant for storing the state of the bean specified by</span></p>
<p class="MsoNormal"><span><span></span>the primary key in the current context and updating the row in </span></p>
<p class="MsoNormal"><span><span></span>the<span></span>table accordingly.This also<br />
is a callback method.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>f)<span></span><b>&#039;ejbActivate&#039; </b>is a callback method which brings a bean into the </span></p>
<p class="MsoNormal"><span><span></span>bean-pool.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>g)<span></span><b><span></span>&#039;ejbPassivate&#039; </b>is a callback method which<br />
removes a bean from </span></p>
<p class="MsoNormal"><span><span></span>the bean-pool.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>Note:</span></p>
<p class="MsoNormal"><span><span></span>In most of the books, we will find that the authors use </span></p>
<p class="MsoNormal"><span>&#039;stored procedure&#039; method using<br />
&#039;PreparedStatement&#039;.</span></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 class="MsoNormal"><span><span></span>It is not absolutely essential. We have used the much simple </span></p>
<p class="MsoNormal"><span>&#039;Statement&#039;<span></span>method, so that it will be easier to follow.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>Some authors opine that the use of Stored procedure does not</span></p>
<p class="MsoNormal"><span>result in any marked improvement in<br />
performance, in network environment!</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></p>
<p class="MsoNormal"><span>//<span></span><b><span></span>customerBean.java</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span>import javax.ejb.*;</span></p>
<p class="MsoNormal"><span>import java.rmi.*;</span></p>
<p class="MsoNormal"><span>import java.sql.*;</span></p>
<p class="MsoNormal"><span>import javax.sql.*;</span></p>
<p class="MsoNormal"><span>import javax.naming.*;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>public class <b>customerBean</b> implements<br />
<b>EntityBean</b></span></p>
<p class="MsoNormal"><span>{</span></p>
<p class="MsoNormal"><span><span></span>public<span></span>String<span></span>key;</span></p>
<p class="MsoNormal"><span><span></span>public<span></span>String<span></span>name;</span></p>
<p class="MsoNormal"><span><span></span>public<span></span>String<span></span>place;<span></span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>public<span></span><b>EntityContext<span></span>context;</b></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>Connection<span></span><span></span>connection;</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>public String <b><span></span>getName</b>()</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span>return<span></span>name;</span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><span></span>public void <b>setName</b>(String<br />
b)</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span>name=b;</span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></p>
<p class="MsoNormal"><span><span></span>public String<span></span><b>getPlace</b>()</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span>return<span></span>place;</span></p>
<p class="MsoNormal"><span><span></span>}<span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>public void <b>setPlace</b>(String<br />
c)</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span>place=c;</span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>private Connection <b>getconnection</b>()<span></span>// this is our own method!</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span>try</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span>Context<span></span>context=<span></span>new InitialContext ();</span></p>
<p class="MsoNormal"><span><span></span><span></span>String<span></span>dsn<span></span>=<span></span><b>&quot;java:comp/env/jdbc/customer&quot;;</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>DataSource<br />
ds=(DataSource)context.lookup(dsn);</b></span></p>
<p class="MsoNormal"><span><span></span><b>connection<span></span>=<span></span>ds.getConnection();</b></span></p>
<p class="MsoNormal"><span><span></span>System.out.println(&quot;Connection obtained&quot;);<span></span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span><span></span>} catch(Exception e1)<span></span>{<span></span>System.out.println(&quot;&quot;+e1);}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b>return<br />
connection;</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span><span></span>public<span></span>String<span></span><b>ejbCreate</b>(String a, String b, String<br />
c)</span></p>
<p class="MsoNormal"><span><span></span>throws<br />
CreateException</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>try</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>key<span></span>=<span></span>a;</span></p>
<p class="MsoNormal"><span><span></span>name=<span></span>b; </span></p>
<p class="MsoNormal"><span><span></span>place = c;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b>connection=getconnection();</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>Statement<span></span>statement<span></span>= connection.createStatement();</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>String<span></span><b>sql</b> = &quot;insert into table1<br />
values(&#039;&quot;+a+&quot;&#039;,&#039;&quot;+b+&quot;&#039;,&#039;&quot;+c+&quot;&#039;)&quot;;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>statement.execute(sql);</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>connection.close();</b></span></p>
<p class="MsoNormal"><span><span></span>System.out.println(&quot;Connection closed&quot;);</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>} catch(Exception<span></span>e1)<br />
{System.out.println(&quot;&quot;+e1);}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b>return<span></span>key;</b></span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span><span></span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>public<span></span>String<span></span><b><span></span>ejbFindByPrimaryKey<span></span></b>(String a)</span></p>
<p class="MsoNormal"><span><span></span>{<span></span></span></p>
<p class="MsoNormal"><span><span></span>try</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>connection=getconnection();</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>Statement<span></span>statement=connection.createStatement();</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>String<span></span>sql=&quot; select * from<br />
table1 where key=&#039;&quot;+a+&quot;&#039; &quot;;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>ResultSet<span></span>rs=statement.executeQuery(sql);</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>connection.close();</b></span></p>
<p class="MsoNormal"><span><span></span>System.out.println(&quot;Connection closed&quot;);</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>} catch(Exception e1) {System.out.println(&quot;&quot;+e1);}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>return<span></span>a;</b></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span><span></span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<span></span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>public<span></span>void <b>ejbLoad()<span></span>//<span></span></b>get<br />
the data from database</span></p>
<p class="MsoNormal"><span><span></span>{ </span></p>
<p class="MsoNormal"><span><span></span>try</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>String<span></span>pk = (String) <b>context.getPrimaryKey();<br />
</b>// <b>* important<span></span></b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>connection<span></span>=<span></span>getconnection();</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>Statement<span></span>statement =<br />
connection.createStatement();</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>String<span></span>sql = &quot;select * from<br />
table1 where key=&#039;&quot;+pk+&quot;&#039; &quot;;</span></p>
<p class="MsoNormal"><span><span></span>ResultSet<span></span>rs=statement.executeQuery(sql);<span></span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span>while(rs.next())</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span>key=rs.getString(1);</span></p>
<p class="MsoNormal"><span><span></span>name=rs.getString(2);</span></p>
<p class="MsoNormal"><span><span></span>place=rs.getString(3);</span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>rs.close();</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b>connection.close();</b></span></p>
<p class="MsoNormal"><span><span></span>System.out.println(&quot;Connection closed&quot;);</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>}<span></span>catch(Exception e1) {<br />
System.out.println(&quot;&quot;+e1); }</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>public<span></span>void<span></span><b>ejbStore()<span></span>//<span></span></b>send<br />
data to database<b></b></span></p>
<p class="MsoNormal"><b><span><span></span>{</span></b></p>
<p class="MsoNormal"><span><span></span>try</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span><span></span><b>connection=getconnection();</b></span></p>
<p class="MsoNormal"><b><span></span></b></p>
<p class="MsoNormal"><span><span></span>Statement<span></span>statement=connection.createStatement();</span></p>
<p class="MsoNormal">&lt;span style=&quot;font-size: 10pt; font-family: &quot;Courier New&amp;quo</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/05/entity-beans-in-ejbbmp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Beans in EJB(CMP)</title>
		<link>http://www.javabeat.net/2008/05/entity-beans-in-ejbcmp/</link>
		<comments>http://www.javabeat.net/2008/05/entity-beans-in-ejbcmp/#comments</comments>
		<pubDate>Sun, 25 May 2008 00:43:14 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[EJB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=332</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>Entity beans are characterized by the following 3 features. a)They are &#039;Persistent&#039;. ( they are stored in hard-disk) b)They are shared by many clients. c)They have , &#039;Primary key&#039;. As already mentioned ,Entity beans can be thought of as a record ( or row) in a table of a relational database. ( This is just [...]</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 class="MsoNormal"><font size="2"><span>Entity<br />
beans are characterized by the following 3 features.</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>a)<span></span>They are <b>&#039;Persistent&#039;</b>. ( they are stored in</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>hard-disk)</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>b)<span></span>They are <b>shared </b>by many clients.</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>c)<span></span>They have , <b>&#039;Primary key&#039;</b>.</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>As already mentioned ,Entity beans can<br />
be thought of as a record ( or row) in a table of a<b> relational </b>database.<br />
( This is just for easy understanding because, the database can also be<b><br />
Object Database</b>, <b>XML</b> database etc.) </span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>Let us consider a simple Java class<br />
named<span></span><b>&#039;customer&#039;</b>. Let this class<br />
have<span></span>just three attributes ,namely<b>,&#039;key&#039;</b>,<span></span><b>&#039;Name&#039;<span></span></b>and <b>&#039;Place&#039;</b>. In a javabean, we would provide <b>accessor<br />
methods,</b> such as <b>&#039;getName()&#039;<span></span></b>&amp;<b><span></span>&#039;setName(</b>String s)etc. for each<br />
attribute. The same method is employed in Entity bean. (<b> Roughly</b>).</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span>Thus,<br />
we deal with Java idiom only and<span></span>this is<br />
more intuitive.If we have an account bean, we can write code for deposit as<br />
follows:</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>int<span></span>n<span></span>= account1.<span></span>getBalance();</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>n=n+400;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>account1.setBalance(n);</span></font></p>
<p class="MsoNormal"><font size="2"><span>Doubtless,<br />
this is much simpler<span></span>and easier than<br />
writing sql code.</span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>Entity beans <b>&#039;persist&#039; </b>(ie) they<br />
are stored in<span></span>Enterprise server&#039;s<b><br />
hard disk </b>and so even if there is a shutdown of the server, the beans<br />
&#039;survive&#039; and can be created again<span></span>from<br />
the hard disk storage.[A <b>session bean </b>is<b> not </b>stored in hard<br />
disk].</span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>A <b><span></span>Session bean </b>, whether it is<span></span>stateless or stateful<span></span>is meant for a<b> single client. </b>But<br />
Entity bean , being a record in a table of a database, is likely to be accessed<br />
by a number of clients . So, they are typically <b>shared</b> by a number of<br />
clients. For the same reason, entity beans should work within <b>&#039;Transaction&#039;</b>.management<span></span>as specified. in the Deployment descriptor.</span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></font></p>
<p class="MsoNormal"><font size="2"><span>[<b> Can<span></span>we use a session<br />
bean<span></span>for accessing a database either for<br />
&#039;select&#039; query or for modifying?</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>Yes. We can, provided<br />
that the application is simple &amp;<span></span>is<br />
not accessed by multiple users . But we should note that the<b> session<br />
bean<span></span>just displays or manipulates a<br />
record in database whereas the entity bean is the record itself!]</b></span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>But, typically in an enterprise situation, a<br />
database will be accessed by thousands of clients concurrently, and the very<br />
rationale for the development of EJB is to tackle the problems which arise<br />
then. That is why, Entity beans are the correct choice for </span><span>Enterprise</span><span><br />
situations.</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>If we think of an entity bean instance as a<br />
record in a table of database, it automatically follows<span></span>that it<span></span>should<span></span>have <b>a primary key for<br />
unique identification </b>of the record..[Many books provide a &#039;primary key<br />
class&#039;.<span></span>But it is not atall<br />
necessary.] But carefully note that it should be a serializable java class. So,<br />
if we provide a primary key as <b>&#039;int&#039; </b>type, we will have to provide a<br />
wrapper class (ie) <b>Integer</b>. This is clumsy. The best and easiest method<br />
is to provide a string type as the primary key. (String class). This is the<br />
method that we will be following in our illustarations.</span></font></p>
<p class="MsoNormal"><font size="2"><span>( We<br />
are using WebLogic 5.1)</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>So, in our example, we are having an<br />
Access<span></span>database named <b>&#039;customer&#039;</b>.This<br />
database has a table known as<b> &#039;table1&#039;</b>. The table has three columns .</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>a) <b>&#039;key&#039;<span></span>(<span></span>primary key field)</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>b) <b>&#039;name&#039;</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>c)<b> &#039;place&#039;</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>( all of them are of<span></span><b>String<span></span></b><span></span>type)</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>We create a table like this without any<br />
entries and then register it in ODBC.( this is the most familiar and easy<br />
approach.We can also use other types of jdbc drivers.)</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>[This does not mean that the records<span></span>have<span></span>to be created only through Entity bean. We can always add, delete and<br />
edit records<b> directly </b>in the table]. </span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<span></span>Entity beans can<span></span>have<span></span>two types of Persistence.</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>a) <b>Container-managed Persistence<span></span>(CMP</b>) </span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>b) <b>Bean-managed Persistence type<span></span>(BMP) </b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>We can declare the type of persistence<br />
required by us in the &#039;Deployment Descriptor&#039;.</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span><span></span>In CMP, the bean designer does not have to<br />
write any sql-related code at all. The necessary sql statements are<br />
automatically generated by the container. The container takes care of<br />
synchronizing the entity bean&#039;s attributes with the corresponding columns in<br />
the table of the database. Such variables are referred to as <b>&#039;container-managed<br />
fields&#039;.</b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span>This<br />
requirement<span></span>also is declared by us in<br />
the Deployment descriptor</span><b><span>.</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span></span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span>With<br />
CMP, the entity bean class does not contain the code that connects to a<br />
database. </span></b><span>. So, we are able to get flexibility by<br />
simply editing the<b> deployment descriptors </b>and <b>weblogic.properties files</b>,<br />
without editing and recompiling the java class files.</span></font></p>
<p class="MsoNormal"><font size="2"><b><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span>What<br />
are the advantages of CMP?</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span><span></span>CMP<span></span>beans<span></span>have two advantages:</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>i)<span></span>less code.</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>ii) the code is independent of<br />
the type of </span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>data store such as Relational<br />
database. </span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span>What<br />
are the<span></span>limitations of CMP?</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span><span></span>If<span></span>we<br />
want to have <b>complex joins between different tables</b>, CMP is not<br />
suitable. In such cases, we should use BMP .</span></font></p>
<p class="MsoNormal"><font size="2"><b><span>============================================================</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span></span></b></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b>EXAMPLE<span></span>FOR<span></span>CMP -ENTITY BEAN</b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>=================================</span></b></font></p>
<p class="MsoNormal"><font size="2"><span>As<br />
before we begin with the Remote Interface file.</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>//<span></span><b><span></span>customerRemote.java</b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>import<br />
javax.ejb.*;</span></font></p>
<p class="MsoNormal"><font size="2"><span>import<br />
java.rmi.*;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>public<br />
interface <b>customerRemote</b> extends <b>EJBObject</b></span></font></p>
<p class="MsoNormal"><font size="2"><span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public String<span></span><b>getName</b>()<span></span>throws<br />
RemoteException;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public void<span></span><b>setName</b>(String<span></span>s) </span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>throws<br />
RemoteException;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public String<span></span><b>getPlace</b>()<span></span>throws RemoteException;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b>setPlace</b>(String s)</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>throws<br />
RemoteException;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span>}</span></font></p>
<p class="MsoNormal"><font size="2"><b><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span></span></b></font></p>
<p class="MsoNormal"><font size="2"><span>Next<span></span>we write the home interfcae.</span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>//<span></span>**********customerHome.java *******************</span></b></font></p>
<p class="MsoNormal"><font size="2"><span>import<br />
javax.ejb.*;</span></font></p>
<p class="MsoNormal"><font size="2"><span>import<br />
java.rmi.*;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>public<span></span>interface<span></span><b>customerHome<span></span></b>extends<span></span><b><span></span>EJBHome</b></span></font></p>
<p class="MsoNormal"><font size="2"><span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span>public<span></span>customerRemote<span></span><b><span></span>create<span></span></b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span>(String<br />
a,<span></span>String b,<span></span>String c)</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>throws<span></span>RemoteException, <b>CreateException;</b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span></span></b></font></p>
<p class="MsoNormal"><font size="2"><span>public<span></span>customerRemote<span></span><b><span></span>findByPrimaryKey<span></span></b>(String a) </span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>throws<span></span>RemoteException, <b>FinderException;<span></span></b></span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>}</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></font></p>
<p class="MsoNormal"><font size="2"><b><span>//customerBean.java</span></b></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span>import<br />
javax.ejb.*;</span></font></p>
<p class="MsoNormal"><font size="2"><span>import<br />
java.rmi.*;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>public<br />
class <b><span></span>customerBean </b>implements<span></span><b><span></span>EntityBean</b></span></font></p>
<p class="MsoNormal"><font size="2"><span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>String<span></span>key;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>String<span></span>name;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>String<span></span>place;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><span></span>public<span></span>String<span></span><b>getName</b>()</span></font></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 class="MsoNormal"><font size="2"><span><span></span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>return<span></span>name;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>}</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>String<span></span><b><span></span>getPlace</b>()</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>return<span></span>place;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>}</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b>setName</b>(String b)</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>name=b;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>}</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b>setPlace</b>(String c)</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>place=c;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>}</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span><b>String</b><span></span><b><span></span>ejbCreate<span></span></b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span>(String<span></span>a, <span></span>String<span></span>b,<span></span>String<span></span>c) </span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>throws<br />
CreateException</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>{</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>this.key<span></span>=<span></span>a;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>this.name=<span></span>b;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>this.place = c;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>return <b>null</b>;<span></span>//<span></span>it should be null!</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b></b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>}</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><span></span>public void<b> ejbPostCreate</b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span></span></b><span>(String<br />
a,String b,String c)</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>throws<br />
CreateException<span></span>{}</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b><span></span>ejbActivate</b>()<span></span>{}</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b>ejbPassivate</b>()<span></span>{}</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b><span></span>ejbRemove</b>()<span></span>{}</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b><span></span>ejbLoad</b>()<span></span>{}</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public<span></span>void<span></span><b><span></span>ejbStore</b>()<span></span>{}</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public void<span></span><b>setEntityContext</b>(EntityContext<br />
ec)<span></span>{ }</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>public void<span></span><b>unsetEntityContex</b>t()<span></span>{ }<span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>}</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></font></p>
<p class="MsoNormal"><font size="2"><span>We now<br />
create<span></span>three<span></span>xml files as given below.</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>1) <b>ejb-jar. xml </b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>2) weblogic-ejb-jar.xml</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>3) </span></b><b><span>weblogic-cmp-rdbms-jar.xml</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span></span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span>These<br />
three files are very important and should be created with utmost care. Remember<br />
that XML is case-sensitive and the DTD (Deployment descriptor) for each file<br />
expects the correct structure of the document. So type exactly as given.(No<br />
formatting..shown here for clarity only)</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></b><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b>ejb-jar. xml </b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>=========</span></b><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&lt;?xml<br />
version=&quot;1.0&quot;?&gt; </span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&lt;!DOCTYPE<br />
ejb-jar PUBLIC</span></font></p>
<p class="MsoNormal"><font size="2"><span>&#039;-//Sun<br />
Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN&#039;</span></font></p>
<p class="MsoNormal"><font size="2"><span>&#039;http://java.sun.com/dtd/ejb-jar_1_1.dtd&#039;&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&lt;ejb-jar&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;enterprise-beans&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b><span></span>&lt;entity&gt;</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;ejb-name&gt;<b>customerBean</b>&lt;/ejb-name&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;home&gt;<b>customerHome</b>&lt;/home&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;remote&gt;<b>customerRemote</b>&lt;/remote&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;ejb-class&gt;<b>customerBean</b>&lt;/ejb-class&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;persistence-type&gt;<b>Container</b>&lt;/persistence-type&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b><span></span>&lt;prim-key-class&gt;java.lang.String&lt;/prim-key-class&gt;</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;reentrant&gt;<b>False</b>&lt;/reentrant&gt;<span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;cmp-field&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><span></span>&lt;field-name&gt;<b>key</b>&lt;/field-name&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><span></span>&lt;/cmp-field&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><span></span>&lt;cmp-field&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;field-name&gt;<b>name</b>&lt;/field-name&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><span></span>&lt;/cmp-field&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;cmp-field&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;field-name&gt;<b>place</b>&lt;/field-name&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;/cmp-field&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b><span></span>&lt;primkey-field&gt;key&lt;/primkey-field</b>&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b>&lt;/entity&gt;</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;/enterprise-beans&gt;<span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;/ejb-jar&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<span></span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b><span></span>weblogic-ejb-jar.xml</b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>====================<span></span></span></b></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&lt;?xml<br />
version=&quot;1.0&quot; ?&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&lt;!DOCTYPE<br />
weblogic-ejb-jar PUBLIC</span></font></p>
<p class="MsoNormal"><font size="2"><span>&quot;-//BEA<br />
Systems, Inc.//DTD WebLogic 5.1.0 EJB//EN&quot;</span></font></p>
<p class="MsoNormal"><font size="2"><span>&quot;http://www.bea.com/servers/wls510/dtd/weblogic-ejb-jar.dtd&quot;&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span>&lt;weblogic-ejb-jar&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;weblogic-enterprise-bean&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;ejb-name&gt;<b>customerBean</b>&lt;/ejb-name&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b>&lt;persistence-descriptor&gt;</b></span></font></p>
<p class="MsoNormal"><font size="2"><b><span></span></b></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b>&lt;persistence-type&gt;</b></span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;type-identifier&gt;WebLogic_CMP_RDBMS&lt;/type-identifier&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;type-version&gt;<b>5.1.0</b>&lt;/type-version&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><span><span></span>&lt;type-storage&gt;<b>META-INF/weblogic-cmp-rdbms-jar.xml</b>&lt;/type-storage&gt;</span></font></p>
<p class="MsoNormal"><font size="2"><b><span><span></span>&lt;/persistence-type&gt;</span></b></font></p>
<p class="MsoNormal"><font size="2"><b><span></span></b></font></p>
<p class="MsoNormal"><font size="2"><span><span></span><b>&lt;persistence-us</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/05/entity-beans-in-ejbcmp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use EJB with Spring framework?</title>
		<link>http://www.javabeat.net/2007/10/using-enterprise-beans-in-spring-environment/</link>
		<comments>http://www.javabeat.net/2007/10/using-enterprise-beans-in-spring-environment/#comments</comments>
		<pubDate>Wed, 24 Oct 2007 11:53:35 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[EJB]]></category>
		<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=134</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>1) Introduction Enterprise Java Beans (EJB) can be used extensively in Spring&#8217;s environment. In this article, we will know about the transparent support available in Spring for using the Stateless and the Stateful Session Beans in Spring.The pre-requisite for this article is some basic knowledge in Spring which can be got by reading the article [...]</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>1) Introduction</h2>
<p align="justify"><em><strong>Enterprise Java Beans (EJB)</strong></em> can be used extensively in Spring&#8217;s environment. In this article, we will know about the transparent support available in Spring for using the <em><strong>Stateless and the Stateful Session Beans</strong></em> in Spring.The pre-requisite for this article is some basic knowledge in Spring which can be got by reading the article in javabeat <a href="http://www.javabeat.net/2007/08/introduction-to-spring-web-framework/">Introduction to Spring Web Framework</a>.</p>
<p align="justify">If you are beginner for spring framework, please read our article on <a href="http://www.javabeat.net/2007/08/introduction-to-spring-web-framework/">introduction to spring framework</a>, <a href="http://www.javabeat.net/2007/07/introduction-to-springs-aspect-oriented-programmingaop/">spring aop</a>, <a href="http://www.javabeat.net/2007/06/introduction-to-spring-mvc-web-framework-web-tier/">spring mvc</a> and <a href="http://www.javabeat.net/2011/03/introduction-to-spring-oxm/www.javabeat.net/category/spring-framework/">list of spring articles</a>. You can find the list of recommended <a href="http://www.javabeat.net/spring-framework-books/">books for spring</a>. Javabeat covers extensive articles on the spring framework. If you are interested in receiving the updates, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</p>
<h2 id="API Support for EJB in Spring">2) API Support for EJB in Spring</h2>
<p align="justify">Let us get into the supporting classes/interfaces available in the Spring Distribution for providing integration support of Enterprise Beans. Let us look at the important classes available in the following packages,</p>
<ul>
<li><strong>org.springframework.ejb.support</strong></li>
<li><strong>org.springframework.ejb.access</strong></li>
</ul>
<h3>2.1) Supporting Base classes</h3>
<p align="justify">This package contains the base supporting classes for creating an enterprise bean. For example, in order to create stateless session bean we can make use of the class <code>'AbstractStatelessSessionBean'</code>. Similarly, the classes <code>AbstractStatefulSessionBean</code> and <code>AbstractJmsMessageDrivenBean</code> correspond to Stateful Session Bean and Message Driven Bean respectively.</p>
<p align="justify">These classes generally form the Facade for the clients. It means that the core logic for doing an operation will be implementated as a <em><strong>POJO (Plain Old Java Object)</strong></em> and the Enterprise Beans merely serve as a facade and delegate the control to POJOs. One of the major disadvantages that the developers would have felt while using the Enterprise Bean running in a EJB Container is that it will be <em><strong>harder for them to perform unit testing</strong></em>. With the use of Spring&#8217;s approach, unit testing becomes much simplier since the implementation classes are POJO.</p>
<p align="justify">The common super-class for all Enterprise Beans is the <code>AbstractEnterpriseBean</code> which contains a well-defined strategy for loading beans from the <em><strong>Application context</strong></em>. The default strategy is to use the <code>ContextJndiBeanFactoryLocator</code> that will create a BeanFactory object with the information taken from one or more classpath locations as specified by the default environment variable,</p>
<p align="justify">Consider the following default Bean Factory locating strategy,</p>
<pre class="brush: java; title: ; notranslate">
&lt;session&gt;

    ...

    &lt;env-entry&gt;
        &lt;env-entry-name&gt;ejb/BeanFactoryPath&lt;/env-entry-name&gt;
        &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
        &lt;env-entry-value&gt;applicationContext.xml&lt;/env-entry-value&gt;
    &lt;/env-entry&gt;

    ...

&lt;/session&gt;
</pre>
<p align="justify">We can see from the above code snippet that the default environment variable corresponds to the default bean factory locator key and in our case it happens to be <code>'ejb/BeanFactoryPath'</code>. This always can be overridden programmatically by calling the method as follows,</p>
<pre class="brush: java; title: ; notranslate">String beanFactoryLocatorKey = &quot;applicationSpecificBeanFactoryLocator&quot;;
bean.setBeanFactoryLocatorKey(beanFactoryLocatorKey);</pre>
<p align="justify">The default <em><strong>BeanFactory Locator</strong></em> is the <code>ContextJndiBeanFactoryLocator</code> and this can also be overridden programmatically by calling the following method,</p>
<pre class="brush: java; title: ; notranslate">BeanFactoryLocator myBeanFactoryLocator = ...;
Bean.setBeanFactoryLocator(myBeanFactoryLocator);</pre>
<h3>2.2) Accessing Enterprise Beans</h3>
<p>The mode of accessing a <em><strong>Stateful Session Bean</strong></em> is different from the way a Stateless Session Bean is accessed. Let us look into the support for accessing a Stateless Session Bean (both local and remote).</p>
<p align="justify">For accessing a <em><strong>Local Stateless Session Bean</strong></em>, we need to use the supporting class <code>LocalStatelessSessionProxyFactoryBean</code>. The configuration for accessing a local stateless session bean is as follows,</p>
<pre class="brush: java; title: ; notranslate">
&lt;bean id=&quot;myBean&quot; 
   &gt;

    &lt;property name=&quot;jndiName&quot;&gt;
        &lt;value&gt;ejb/myBeanService&lt;/value&gt;
    &lt;/property&gt;

    &lt;property name=&quot;businessInterface&quot;&gt;
        &lt;value&gt;MyComponentService&lt;/value&gt;
    &lt;/property&gt;

&lt;/bean&gt;
</pre>
<p align="justify">There are two properties for configuring a local stateless session bean using <em><strong>Proxy mechanism</strong></em>. The first property <code>'jndiName'</code> is the Jndi name of the bean which can be used by the <em><strong>Jndi Bean Factory object</strong></em> to perform lookup operation. The second property <code>'businessInterface'</code> defines the business interface for which the implementation will be generated by the Spring container and delegation will be made to the actual implementation.</p>
<p align="justify">Similarly, for accessing the <em><strong>Remote Stateless Session Bean</strong></em>, the class <code>SimpleRemoteStatelessSessionProxyFactoryBean</code> has to be used instead of <code>LocalStatelessSessionProxyFactoryBean</code>. The properties <code>'jndiName'</code> and <code>'businessInterface'</code> will still be applicable.</p>
<p align="justify">There is no direct support in Spring for accessing the Stateful Session Beans using Proxy mechanisms. However, a convenient way is provided in the form of <code>JndiObjectFactoryBean</code>.</p>
<p align="justify">Let us consider the following configuration,</p>
<pre class="brush: java; title: ; notranslate">
&lt;bean id=&quot;myServiceHome&quot; 
   &gt;

    &lt;property name=&quot;jndiName&quot;&gt;
        &lt;value&gt;ejb/myService&lt;/value&gt;
    &lt;/property&gt;

&lt;/bean&gt;
</pre>
<p align="justify">In the above Xml snippet, we have configured an instance of a <em><strong>EJB Home interface</strong></em> with the help of <code>JndiObjectFactoryBean</code>. In a traditional EJB Applicaition, we have to manually do a <em><strong>JNDI</strong></em> lookup using the <code>InitialContext</code> to get a reference to the <em><strong>EJB Home object</strong></em>. But in Spring, the lookup operation is made easy merely by putting some configuration information,</p>
<p align="justify">We would have to use the following approach to get a reference to the Stateful Session Bean,</p>
<pre class="brush: java; title: ; notranslate">ApplicationContext context = .... ; // Initialize the Application context.
MyServiceHome myServiceHome = (MyServiceHome)context.getBean(&quot;myServiceHome&quot;);

MyService myService = myServiceHome.create();
// Perform the required business logic using this bean.
.
.
.</pre>
<h2>3) Creating a Stateless Session Bean</h2>
<p align="justify">In this section, let us see an example for creating a simple <em><strong>Stateless Session</strong></em> using the supporting Spring APIs. One of the major goals of Spring is to facilitate unit testing in a much simpler way, which means that the implementation classes should not depend on the third-party library classes. Let us develop a Hello Service Application.</p>
<h3>3.1) The Business Interface</h3>
<p align="justify">Let us define the <em><strong>business interface</strong></em> for our Application as follows,</p>
<p><strong>HelloService.java</strong></p>
<pre class="brush: java; title: ; notranslate">package javabeat.net.articles.spring.ejb.integration.stateless;

public interface HelloService {

    public String hello();

}</pre>
<p align="justify">The interface has a single method <code>hello()</code> which is intended to be given implementation by some classes.</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>
<h3>3.2) The Implementation class</h3>
<p><strong>HelloServiceImpl.java</strong></p>
<pre class="brush: java; title: ; notranslate">package javabeat.net.articles.spring.ejb.integration.stateless;

public class HelloServiceImpl implements HelloService{

    public String hello() {
        return &quot;Hello&quot;;
    }

}</pre>
<p>The above class provides a simple implementation for the business interface <code>HelloService</code>. The implementation merely returns the string &#8220;Hello&#8221;. Note that a real implementation may contain much sophisticated logic by maintaining transaction, accessing the database, etc.. It is evident that the above <em><strong>business interface</strong></em> follows the POJO standard which means that it will be easier to perform <em><strong>Unit Testing</strong></em> in isolation by providing <em><strong>Mock Implementation</strong></em>.</p>
<h3>3.3) The EJB Local Object</h3>
<p><strong>HelloServiceLocal.java</strong></p>
<pre class="brush: java; title: ; notranslate">package javabeat.net.articles.spring.ejb.integration.stateless;

import javax.ejb.EJBLocalObject;

public interface HelloServiceLocal extends HelloService, EJBLocalObject{

}</pre>
<p align="justify">Let us define a <strong>Local interface</strong> by extending the <code>EJBLocalObject</code>. Note that this interface also extends our business interface <code>HelloService</code>. This is the <em><strong>client-facing interface</strong></em> meaning that the client will invoke all the business operation through this interface.</p>
<h3>3.4) The EJB Home Object</h3>
<p align="justify">Home interfaces follow Factory patterns to return either Local or Remote objects. Usually clients will obtain a reference to the Home interface through JNDI, then will create the Local (or Remote) interface by using one of the create methods.</p>
<p><strong>HelloServiceHome.java</strong></p>
<pre class="brush: java; title: ; notranslate">package javabeat.net.articles.spring.ejb.integration.stateless;

import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;

public interface HelloServiceHome extends EJBLocalHome {

    public HelloServiceLocal create() throws CreateException;

}</pre>
<p align="justify">The above Home interface contains a create() method that returns a <code>HelloServiceLocal</code> object.</p>
<h3>3.5) The Hello Service EJB</h3>
<p><strong>HelloServiceEjb.java</strong></p>
<pre class="brush: java; title: ; notranslate">package javabeat.net.articles.spring.ejb.integration.stateless;

import javax.ejb.CreateException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.ejb.support.AbstractStatelessSessionBean;

public class HelloServiceEjb extends AbstractStatelessSessionBean implements HelloService{

    private HelloService helloService;

    protected void onEjbCreate() throws CreateException {
        BeanFactory beanFactory = getBeanFactory();
        helloService = (HelloService)beanFactory.getBean(&quot;helloService&quot;);
    }

    public String hello() {
        return helloService.hello();
    }
}</pre>
<p align="justify">This is the real EJB Component that needs to be deployed to the Server. Note that this class extends the <code>AbstractStatelessSessionBean</code> so that it contains the default <em><strong>Bean Factory Locator</strong></em> and some other stuffs. The EJB Components developed through Spring&#8217;s style will merely serve as a facade and the original implementation will be delegated to the POJO Business Implementation class.</p>
<p align="justify">In the above case, even though we have a method called <code>hello()</code> (this method must be defined since the <code>HelloServiceEjb</code> is implementing the <code>HelloService</code> interface), the implementation simply delegates the control to <code>HelloServiceImpl.hello()</code>. One important point to be mentioned here is the need for instantiation the <code>HelloService</code> object. The default Bean Factory object (<em><strong>Jndi Bean Factory Locator</strong></em>) is referenced and an instance of the implementation class is acquired by calling the <code>getBean()</code> method.</p>
<h3>3.6) Bean Configuration file</h3>
<p><strong>spring-stateless-ejb.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE beans PUBLIC &quot;-//SPRING//DTD BEAN//EN&quot;
&quot;http://www.springframework.org/dtd/spring-beans.dtd&quot;&gt;

&lt;beans&gt;
&lt;bean id=&quot;helloService&quot;
/&gt;

&lt;/beans&gt;</pre>
<p align="justify">The preceding <code>HelloEjbComponent</code> instantiates an implementation of HelloService through the identifier “helloService”. This identifier should match the one that is defined in the configuration file.</p>
<h3>3.7) Deployment Descriptor</h3>
<p><strong>ejb-jar.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;ejb-jar&gt;

    ...

    &lt;session&gt;
        &lt;ejb-name&gt;HelloServiceEjb&lt;/ejb-name&gt;
        &lt;local-home&gt;
            javabeat.net.articles.spring.ejb.integration.stateless.HelloServiceHome
        &lt;/local-home&gt;
        &lt;local&gt;
            javabeat.net.articles.spring.ejb.integration.stateless.HelloServiceLocal    
        &lt;/local&gt;
        &lt;ejb-class&gt;
            javabeat.net.articles.spring.ejb.integration.stateless.HelloServiceEjb
        &lt;/ejb-class&gt;
        &lt;session-type&gt;Stateless&lt;/session-type&gt;
        &lt;transaction-type&gt;Container&lt;/transaction-type&gt;

        &lt;env-entry&gt;
            &lt;env-entry-name&gt;ejb/BeanFactoryPath&lt;/env-entry-name&gt;
            &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
            &lt;env-entry-value&gt;spring-stateless-ejb&lt;/env-entry-value&gt;
        &lt;/env-entry&gt;
    &lt;/session&gt;    

    ...

&lt;/ejb-jar&gt;
</pre>
<p align="justify">The above deployment descriptor is similar to a traditional deployment descriptor. One thing to note is the environmental entries, that contains a key called <code>'ejb/BeanFactoryPath'</code> which contains the path to the configuration file. As mentioned in the preceding section, the default Bean Factory Locator key is <code>'ejb/BeanFactoryPath'</code> and this can always be overridden by specifying the property <code>beanFactoryLocatorKey</code>.</p>
<h3>3.8) The Client&#8217;s Configuration file</h3>
<p><strong>client-spring-stateless-ejb</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;beans&gt;

    &lt;bean id=&quot;echoService&quot; 
   &gt;

        &lt;property name=&quot;jndiName&quot;&gt;
            &lt;value&gt;java:comp/env/helloService&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;businessInterface&quot;&gt;
            &lt;value&gt;javabeat.net.articles.spring.ejb.integration.stateless.HelloService&lt;/value&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p align="justify">The client accessing an Enterprise Bean can be a <em><strong>standalone Remote client</strong></em>, or a <em><strong>Servlet</strong></em> or even can be another <em><strong>Enterprise Bean</strong></em>. In all these cases, the client must be aware of the factors like locating the Bean when given a <em><strong>Jndi name</strong></em> and to get a appropriate reference to the <em><strong>business interface</strong></em>.</p>
<p align="justify">In the above configuration file, the property <code>'jndiName'</code> is used to locate the <em><strong>Enterprise Bean</strong></em> object. The business interface is <code>HelloService</code> which means a proxy object for <code>HelloService</code> interface will be returned simply because we have configured the bean to use <code>LocalStatelessSessionProxyFactoryBean</code>.</p>
<h2>4) Conclusion</h2>
<p align="justify">A major drawback in developing a J2EE Application that makes use of Enterprise Java Beans for doing a business operation is the un-necessary complications available for the clients like looking up the Home object, creating the reference etc.., and it is impossible to do Unit testing for the Enterprise Bean as these beans always reside within the Container. However with Spring&#8217;s way of accessing Enterprise Beans this has been simplified.</p>
<p align="justify">If you have any questions on the spring framework integration with email, please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about <a href="http://www.javabeat.net/2007/08/introduction-to-spring-web-framework/">spring framework</a>, <a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">interview questions</a>, <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring and hibernate integration</a>,etc. If you are looking for the detailed knowledge, buy any of the following <a href="http://www.javabeat.net/spring-framework-books/">books for the spring framework</a>.</p>
<ul>
<li><a href="http://www.flipkart.com/spring-action-9350042096/p/itmdfjfg9hhwjk2z?pid=9789350042090&amp;affid=suthukrish" target="_blank">Spring In Action:Covers Spring 3.0</a></li>
<li><a href="http://www.flipkart.com/spring-batch-action-9350042592/p/itmd4v8gru2gxxvm?pid=9789350042595&amp;affid=suthukrish" target="_blank">Spring Batch In Action</a></li>
<li><a href="http://www.flipkart.com/spring-dynamic-modules-action-9350040621/p/itmdf85jgmxfv8hk?pid=9789350040621&amp;affid=suthukrish" target="_blank">Spring Dynamic Modules In Action</a></li>
</ul>
<p><strong>If you would like to receive the future java articles from our website, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</strong></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/10/using-enterprise-beans-in-spring-environment/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
