Academic Tutorials



English | French | Portugese | German | Italian
Home Advertise Payments Recommended Websites Interview Questions FAQs
News Source Codes E-Books Downloads Jobs Web Hosting
Chats

Weblogic Tutorial
WebLogic Tutorial Introduction
The WebLogic Workshop Development Environment
Developing Applications
Applications and Projects
Workshop File Types
Debugging Your Application
Managing the Build Process
Compile a Single Java File
Source Control Systems
Message Logging
Working with Java Controls
Developing Web Applications
Designing Asynchronous Interfaces
Handling XML with XMLBeans
Building Integration Applications
Building Portal Applications
Developing Enterprise JavaBeans
The Life Cycle of an Entity Bean
Session Beans
Developing Message-Driven Beans
WebLogic Workshop Security Overview
Deploying an Application

HTML Tutorials
HTML Tutorial
XHTML Tutorial
CSS Tutorial
TCP/IP Tutorial
CSS 1.0
CSS 2.0
HLML
XML Tutorials
XML Tutorial
XSL Tutorial
XSLT Tutorial
DTD Tutorial
Schema Tutorial
XForms Tutorial
XSL-FO Tutorial
XML DOM Tutorial
XLink Tutorial
XQuery Tutorial
XPath Tutorial
XPointer Tutorial
RDF Tutorial
SOAP Tutorial
WSDL Tutorial
RSS Tutorial
WAP Tutorial
Web Services Tutorial
Browser Scripting
JavaScript Tutorial
VBScript Tutorial
DHTML Tutorial
HTML DOM Tutorial
WMLScript Tutorial
E4X Tutorial
Server Scripting
ASP Tutorial
PERL Tutorial
SQL Tutorial
ADO Tutorial
CVS
Python
Apple Script
PL/SQL Tutorial
SQL Server
PHP
.NET (dotnet)
Microsoft.Net
ASP.Net
.Net Mobile
C# : C Sharp
ADO.NET
VB.NET
VC++
Multimedia
SVG Tutorial
Flash Tutorial
Media Tutorial
SMIL Tutorial
Photoshop Tutorial
Gimp Tutorial
Matlab
Gnuplot Programming
GIF Animation Tutorial
Scientific Visualization Tutorial
Graphics
Web Building
Web Browsers
Web Hosting
W3C Tutorial
Web Building
Web Quality
Web Semantic
Web Careers
Weblogic Tutorial
SEO
Web Site Hosting
Domain Name
Java Tutorials
Java Tutorial
JSP Tutorial
Servlets Tutorial
Struts Tutorial
EJB Tutorial
JMS Tutorial
JMX Tutorial
Eclipse
J2ME
JBOSS
Programming Langauges
C Tutorial
C++ Tutorial
Visual Basic Tutorial
Data Structures Using C
Cobol
Assembly Language
Mainframe
Forth Programming
Lisp Programming
Pascal
Delphi
Fortran
OOPs
Data Warehousing
CGI Programming
Emacs Tutorial
Gnome
ILU
Soft Skills
Communication Skills
Time Management
Project Management
Team Work
Leadership Skills
Corporate Communication
Negotiation Skills
Database Tutorials
Oracle
MySQL
Operating System
BSD
Symbian
Unix
Internet
IP-Masquerading
IPC
MIDI
Software Testing
Testing
Firewalls
SAP Module
ERP
ABAP
Business Warehousing
SAP Basis
Material Management
Sales & Distribution
Human Resource
Netweaver
Customer Relationship Management
Production and Planning
Networking Programming
Corba Tutorial
Networking Tutorial
Microsoft Office
Microsoft Word
Microsoft Outlook
Microsoft PowerPoint
Microsoft Publisher
Microsoft Excel
Microsoft Front Page
Microsoft InfoPath
Microsoft Access
Accounting
Financial Accounting
Managerial Accounting
Network Sites


Developing Enterprise JavaBeans


Previoushome Next






Developing Enterprise JavaBeans


These topics show how to develop Enterprise JavaBeans. WebLogic Workshop provides you with the tools to make EJB development much easier, taking care of many implementation details for you and allowing you to focus on design.


A D V E R T I S E M E N T

Note. WebLogic Workshop 8.1 supports the development, importing, and building of EJB2.0 compliant Enterprise JavaBeans. In addition, the WebLogic Platform supports the deployment only of EJB1.1 compliant Enterprise JavaBeans.




Getting Started with EJB Project


When you are building WebLogic platform applications, EJB project is the development environment for Enterprise JavaBeans. EJB project provides a number of tools that facilitate the development of the EJBs which encompass the business logic for your enterprise application. This topic provides an overview of EJBs and EJB project in platform applications. It includes the following sections:
  • What is an Enterprise JavaBean?
  • What is EJB Project?
  • EJB Project and ejbgen Tags
  • Building and Deploying EJBs
  • What are EJB Controls?


What is an Enterprise JavaBean?


An EJB is a server-side component that encapsulates the business logic of an application. The business logic is the code that fulfills the purpose of the application, as opposed to code that provides infrastructure and plumbing for the application. In an inventory control application, for example, the EJBs might implement the business logic in methods called checkInventoryLevel and orderProduct. By invoking these methods, remote clients can access the inventory services provided by the application.

EJBs always execute within an EJB container, which provides system services to EJBs. These services include transaction management, persistence, pooling, clustering and other aspects of infrastructure. The J2EE and EJB architecture is built on a number of underlying technology standards, such as the JDBC API for database connectivity, JMS for messaging, and JNDI for naming and directory functionality. To learn more about these technology standards, see your favorite J2EE documentation and http://java.sun.com.

In J2EE 1.4 there are three types of EJBs: session, entity, and message-driven. Each of these types is described briefly in the following sections.


Session EJBs


A session EJB is used to execute business tasks for a client on the application server. The session EJB might execute only a single method for a client, in the case of stateless session beans, or it might execute several methods for that same client, in the case of stateful session beans. A session bean is never shared by clients. A session EJB is not persistent, so when the client terminates, its session EJB disconnects and is no longer associated with the client.


Entity EJBs


An entity EJB represents a business object in a persistent storage mechanism. Some examples of business objects are customers, orders, and products. The persistent storage mechanism is a relational database. Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table. Unlike session beans, entity beans are persistent, allow shared access, have primary keys, and may participate in relationships with other entity beans.


Message-Driven EJBs


A message-driven EJB is an enterprise bean that is able to listen for Java Message Service (JMS) messages. The messages may be sent by any JMS-compliant component or application. Message-driven EJBs provide a mechanism for J2EE applications to participate in relationships with message-based legacy applications.


EJB Interfaces


EJB 2.0 exposes four types of interfaces for session and entity beans, called the local home interface, the local business interface (or simply, the local interface), the remote home interface, and the remote business interface (or simply, the remote interface). Client applications can obtain an instance of the EJB with which to communicate by using the remote home interface. The methods in the remote home interface are limited to those that create or find EJB instances. Once a client has an EJB instance, it can invoke methods of the EJB's remote business interface to do real work. The business interface directly accesses the business logic encapsulated in the EJB. Interactions between EJBs defined in the same WebLogic Workshop application, as well as interactions between EJBs and web services or page flows in the same WebLogic Workshop application, can use the local interfaces instead, which provides a performance advantage over remote interfaces. In other words, the local home and business interfaces define the methods that can be accessed by other beans, EJB controls, web services, and page flows in the same WebLogic Workshop application, while the remote home and business interfaces define the methods that can be accessed by other applications.

Message-driven beans do not have these interfaces, because these beans' methods do not get invoked directly by other beans or client applications. Instead they process messages from client applications or other EJBs that are delivered via the Java Message Service (JMS). When a message is delivered, the EJB container calls the message-driven bean's onMessage method to process the message. For more information on Java Message Service, see your favorite J2EE documentation. WebLogic Workshop also provides JMS controls to work with a Java Message Service. For more information, see JMS Controls.


Deployment Descriptor


During runtime, information about how EJBs should be managed by the EJB container is read from a deployment descriptor. The deployment descriptor describes the various beans packaged in an EJB JAR file, settings related to transaction management, and EJB QL for find methods, to name a few examples. Deployment descriptor settings can be changed without having to make changes to the actual beans, allowing for the fine-tuning of EJBs.


EJB JAR


The EJB JAR contains one or more EJBs, including their interface definitions, any related Java classes that are being used by the EJBs, and a deployment descriptor describing these EJBs.


What is EJB project?


EJB project is the development environment for session, entity, and message-driven beans in a WebLogic platform application. An EJB project contains one or more EJBs. A WebLogic platform application can have one or more EJB projects, as well as other types of projects such as web (service) projects, and Java control projects, thereby creating an integrated development environment.

EJB project provides a Design View, property editor, building and debugging windows, and various wizards to facilitate the design and development of EJBs. For instance, in Design View you can define business (component) methods, define CMP fields, and define methods for local and/or remote interfaces. A property editor is used to edit deployment descriptor settings and ejbgen tag settings (see below). Various wizards make it easy to import EJBs into EJB projects, create ejbCreate methods, and define entity relationships. Build and debugging windows are used to monitor the build process and to monitor the EJB when running/debugging the application. For more information on the visual environment, see Summary of IDE Windows for EJB Project. For step-by-step instructions on using the Design View and the various wizards, see the 'How Do I...?' section Enterprise JavaBeans.

A key advantage of developing EJBs in EJB project is that one file is used to store the definition of the EJB class, its interfaces, and deployment descriptor specific settings. Instead of managing the overhead of using several java files to store this information, one file with an ejb extension is used to represent an EJB. This is accomplished by using ejbGen, which is described next.


EJB Project and ejbgen Tags


During Enterprise JavaBean development, special Javadoc tags with the prefix ejbgen are inserted in the EJB source file. These ejbgen tags are used to mark methods to be exposed in remote and home interfaces, store deployment descriptor settings, and various other types of information. In many cases you will not have to add these ejbgen tags directly. Instead these tags are added when, for example, you define a business methods to be local, or create a primary key field for an entity bean. You can also use the property editor to edit ejbgen tag settings.

The use of a single EJB file is only for development purposes. When you build an EJB Project, the build process uses these tags to generate the various interfaces and deployment descriptor files as prescribed in the J2EE specification.


Building and Deploying EJBs


When you build an EJB project, the EJBs' source code is compiled and checked for errors. The build output of an EJB project is an EJB JAR, containing the various JAVA and CLASS files for the bean class, its interfaces, and any dependent value or primary key classes, as well as the deployment descriptor for these beans. After the build completes, the beans are (re)deployed on the server. You can also deploy, undeploy and redeploy EJBs separately from building.


What are EJB Controls?


When you want to use an EJB from a client application (such as a page flow), you must look up the EJB in the JNDI registry and obtain the EJB's home interface, before you can create an EJB instance and invoke the EJB's business methods. EJB controls provide an alternative approach to make locating and referencing the EJB easy. Once you have created the EJB control, the client application can define the EJB control and use its methods, which have the same method names as the EJB it controls, to execute the desired business logic without having to be involved with locating and referencing the EJB itself. In other words, EJB controls take care of the preparatory work necessary to use an EJB, allowing you to focus on the business logic instead. For more information, see EJB Controls.


What are CMP Entity Beans?


An entity bean represents a business object in a persistent storage mechanism. In other words, entity beans are used to model real-world objects with properties that need to be stored and remembered over time. Examples of business objects are customers, products, orders, credit cards, and addresses. Typically, each entity bean has an underlying table in a relational database, and each bean instance corresponds to a row in that table. An entity bean has one or more primary keys, or unique indices, to uniquely identify an object, that is, a particular record in the database.

Container-managed persistence (CMP) entity beans are entity beans for which the EJB container takes care of mapping property and relationship fields to the underlying database and knows how to insert, update, and delete data for an entity bean.


Home and Business Interfaces


An entity bean can have four different interfaces, called the local home interface, the local business interface (or simply, the local interface), the remote home interface, and the remote business interface (or simply, the remote interface). The local interfaces define the bean's methods that can be used by other EJBs, EJB controls, web services, and page flows defined within the same application. That is, if you define an entity bean and only plan to use it within that application, you can use local interfaces. In contrast, the remote interfaces define the bean's methods that be invoked by EJBs, EJB controls, web services, and page flows defined in other applications.

To determine what interfaces are defined for an entity bean, ensure you are in Design View and go to the Naming section in the Property Editor. The Remote EJB and Local EJB sections refer to the remote and local interfaces; within each section the Home class name refers to the home interface, and the Bean class name refers to the business interface. In Source View, the attributes are part of the @ejbgen:file-generation Annotation. When you define a new entity bean, by default only the local interfaces are defined, reflecting the design assumption that in your model entity beans are not accessed directly by other client applications but indirectly, with session or message-driven beans defined in the same application as intermediaries.

Client applications and other session or entity beans can obtain an instance of an entity bean with which to communicate by using methods in the (remote or local) home interface. Methods in the home interface include create methods, the findByPrimaryKey method, and other finder methods that return a single reference or a set of references to entity bean instances. In addition, Home methods are defined in the local interface. The (remote or local) business interface contains the methods that manipulate an entity bean instance. These methods include field accessor (getter and setter) methods and component methods.


CMP Fields


Container-managed persistence (CMP) fields contain the business object's properties. For example, a Customer bean might contain first name, last price, gender, and age fields. Because the EJB container takes care of the mapping of these properties to a database, CMP fields are virtual fields in an entity bean; that is, these fields are not defined in the entity bean itself but correspond to columns in the database table. The entity bean only defines the accessor (getter and setter) methods. A CMP field can serve as a primary key field, meaning that this field uniquely identifies the entity bean instance or, if multiple primary keys are defined, in combination with the other primary keys uniquely identifies the entity bean instance. For more information, see How Do I: Define a Container-Managed Persistence (CMP) Field?


Create Methods


An ejbCreate method is used to create a new instance of an entity bean, that is, insert a new record in the underlying database. At least one ejbCreate method must be defined, but multiple ejbCreate methods are not uncommon. Each ejbCreate method defined for an entity bean has the signature public ejbCreate(parameters). The can be a primitive type, such as Integer, when a single primary key is defined, or it can be a separate primary key class. By default, WebLogic auto-generates a primary key class, with the name provided as an attribute in the @ejbgen:file-generation Annotation. To find out which primary key class is used for an entity bean, ensure you are in Design View and go to the General section in the Property Editor. In Source View, this attribute is part of the @ejbgen:entity Annotation.

Multiple ejbCreate methods can only be distinguished by their parameter composition. In the home interface, ejbCreate methods are exposed as create methods and can correspondingly be distinguished only by the unique set of parameters each one requires. For more information, see How Do I: Add a Create Method to an Entity Bean?


Component Methods


Component methods are the business methods that are invoked on an entity bean instance. A simple example of a business method is updateCustomer(firstName, lastName, age), which is used to update the customer's first name, last name and age. This method will in turn invoke the bean's setFirstName, setLastName and setAge methods to update the CMP fields holding this information. For more information, see How Do I: Add a Component Method to an Entity or Session Bean?


Home Methods


A home method is a business method that relates to the entity bean but is not specific to a single bean instance. For instance, a Customer bean might have a home method returning the total number of customers between 25 and 35 years of age. A home method is defined as a ejbHome method in the bean, and is exposed as a method on the bean's home interface. For example the method ejbHomeGetNCustomers defined in the bean class is exposed as getNCustomers in its home interface. For more information, see How Do I: Add a Home Method to an Entity or Session Bean? and the Home Methods Sample.


Finder and Select Methods


Finder and select methods are methods that execute queries on the database, using the EJB QL or WebLogic QL query languages. A finder method is defined in the bean's home interface and returns a reference to a single bean instance or to a set of references to bean instances. In contrast, a select method is not defined in any interface and can only be invoked internally, for instance by a bean's component method. A select method can return a reference to a single bean instance, a set of bean instances, or one or more individual CMP fields.

In addition to the finder and select methods defined for the bean, the method findByPrimaryKey() is automatically defined by WebLogic in the home interface(s) defined for the bean class. This method returns a reference to the bean instance that is uniquely defined by the method's parameter. As before, the can be a primitive type, such as Integer, when a single primary key is defined, or it can be a separate primary key class. To find out which primary key class is used for an entity bean, ensure you are in Design View and go to the General section in the Property Editor. In Source View, this attribute is part of the @ejbgen:entity Annotation.

For more information on how to define finder or select methods, see How Do I: Add a Finder Method to an Entity Bean? and How Do I: Add a Select Method to an Entity Bean? For more information on the EJB QL and WebLogic QL query languages, see Query Methods and EJB QL, the Finder Methods Sample, and the Select Methods Sample.


Relations


Entity relationships are used to model dependencies between business objects. For example, a customer can have one or more credit cards, and a product has a manufacturer. Relations between two entity beans can be defined such that for a customer, you can easily access its credit cards by using the accessor method getCreditCards. The entity relation accessor methods, also known as the CMR field accessor methods are defined in the bean's business interface. For more information, see Entity Relationships, How Do I: Add a Relation to an Entity Bean?, and Tutorial: Enterprise JavaBeans.


Other Methods


An entity bean has several predefined methods, as well as a number of callback methods, invoked by the EJB container during certain operations, that an entity bean must implement. In WebLogic these callback methods are by default automatically implemented. In many cases you will find it unnecessary to use these methods, with the possible exception of the remove methods used to remove an entity bean instance. To learn more about predefined methods and remove methods in particular, see Defining an Entity Bean. To learn more about callback methods, see the Callback Methods section of that same topic and The Life Cycle of an Entity Bean.


Creating an Entity Bean


To create an entity bean, you can choose one of the following methods:

  • Create an entity bean from scratch. If you are designing a new entity bean in EJB project, you can define a new entity bean. To find out exactly how to do this, see How Do I: Create an Enterprise JavaBean? When you create a new entity bean, by default the local interfaces and various other defaults are defined. For more details, see @ejbgen:file-generation Annotation.
  • Create an entity bean from a database table. If you have already designed a database table and want to create an entity bean with CMP fields mapped to the database columns, you can create an entity bean from a database table. To find out exactly how to do this, see How Do I: Generate an Entity Bean from a Database Table? In addition to mapping the CMP fields and defining an ejbCreate method with the (compound) primary key as the parameter, by default local interfaces and various other defaults are defined. For more details, see @ejbgen:file-generation Annotation. After you have created an entity bean from a database table, you can further expand its definition, including making changes that will require changes to the underlying database table.
  • Import an entity bean. If you have developed entity beans in another development environment, you can import these into WebLogic. To import an EJB, you need the EJB Jar file as well as the source files. You can import multiple EJBs at the same time. If you import multiple entity beans with defined entity relations, these relation definitions will be imported as well. For more information, see How Do I: Import an Enterprise JavaBean? After you have imported an entity bean, you can enhance its definition.

    Note. If you have existing entity beans that you plan to invoke in the application, for instance via another EJB or an EJB control, but you do not intend to change their definitions, you can suffice by adding the EJB Jar to the application. For more information, see How Do I: Add an Existing Enterprise JavaBean to an Application?


Automatic Table Creation


When you are developing a new entity bean using any of the three methods specified above, you can make iterative development easier by enabling automatic table creation. You can have WebLogic create the table when it is not present, and you can allow WebLogic to drop an existing table and recreate it if the definition of the entity bean does not match the table specifications. You enable automatic table creation using the create-table property located in the JAR Settings section of the Property Editor. The default setting is CreateOnly. To recreate a table if the definition of the entity bean does not match the table specification, use DropAndCreate. For more information regarding the possible settings, see @ejbgen:jar-settings Annotation.

Note. Automatic table creation is meant to facilitate development, and is disabled in production mode.


Defining a Basic Entity Bean


The following figure shows the design view of a basic entity bean called ProductBean:

This bean was developed by defining it from scratch, adding the two CMP fields, labeling one of these as the primary key, and creating an ejbCreate method (for more details, see How Do I: Add a Create Method to an Entity Bean?). These steps were accomplished in design view. This entity bean allows you to add a new product, find a product using its primary key, and getting and setting its CMP field values. The source code of this bean is given below:

package myBeans;

import javax.ejb.*;
import weblogic.ejb.*;

/**
 * @ejbgen:entity prim-key-class="java.lang.String"
 *   ejb-name = "Product"
 *   data-source-name="cgSampleDataSource"
 *   table-name = "product"
 *   abstract-schema-name = "Product"
 *
 * @ejbgen:jndi-name
 *   local  = "ejb.ProductLocalHome"
 *
 * @ejbgen:file-generation local-class = "True" local-class-name = "Product" local-home = "True" 
 *    local-home-name = "ProductHome" remote-class = "False" remote-home = "False" 
 remote-home-name = "ProductRemoteHome" 
 *    remote-class-name = "ProductRemote" value-class = "False" value-class-name = "ProductValue" 
 pk-class = "True"
 *
 */
abstract public class ProductBean extends GenericEntityBean implements EntityBean
{

    /**
     * @ejbgen:cmp-field primkey-field="true" column="Name"
     * @ejbgen:local-method
     */
    public abstract String getName();

    /**
     * @ejbgen:local-method
     */
    public abstract void setName(String arg);

    /**
     * @ejbgen:cmp-field column="Price"
     * @ejbgen:local-method
     */
    public abstract double getPrice();

    /**
     * @ejbgen:local-method
     */
    public abstract void setPrice(double arg);

    public java.lang.String ejbCreate(java.lang.String Name, double Price)
    {
      setName(Name);
      setPrice(Price);

      return null; // FIXME return PK value 
    }

    public void ejbPostCreate(java.lang.String Name, double Price)
    {
    }
}

In WebLogic, all the information needed to make an entity bean is stored in a single file, instead of separate JAVA files for the bean class, the local business interface, the local home interface, its primary key class, and so forth. When you build an EJB, these other classes are auto-generated. Various ejbgen annotations are used to hold the information required to make this generation possible. For example, the @ejbgen:file-generation annotation specifies the names of the local home and business interface for the ProductBean. The @ejbgen:local-method annotations on the accessor methods specify that these methods are defined in the local business interface. To verify that these JAVA and corresponding CLASS files are generated, expand the JAR file created during a build (located in the Modules folder in the Application pane), and locate and open the generated files in the folder reflecting the package name. For the ProductBean, the ProductBean.java (bean definition), Product.java (local interface definition), and ProductHome.java (local home interface definition) files are auto-generated.

If the ProductBean were to use multiple primary keys, the ProductBeanPK.java file containing the definition of the compound primary key class would also be auto-generated. For instance, the following figure shows a redefined ProductBean with an additional primary key manufacturer:

Notice in the above figure that the compound primary key is the return value of the ejbCreate method. Also, the auto-generated method findByPrimaryKey(myBeans.ProductBeanPK primaryKey) uses the compound primary key to obtain a bean instance reference.

Finally a value object class can also be auto-generated. For more information, see the Value Object Sample


Removing an Entity Bean Instance


Any entity bean must define at least one ejbCreate method to create a new instance. Also, the EJB container automatically defines the findByPrimaryKey method in the home interface(s), which return a bean instance using its primary key (class) as the method parameter. In addition, all the bean's interfaces will extend a particular interface which contains various useful methods. Specifically:

  • The local interface extends javax.ejb.EJBLocalObject
  • The local home interface extends javax.ejb.EJBLocalHome
  • The remote interface extends javax.ejb.EJBObject
  • The remote home interface extends javax.ejb.EJBHome

Complete details about these interfaces and the methods they define can be found in your favorite J2EE documentation and the API reference at http://java.sun.com. One of the more frequently used methods provided by these 'extended' interfaces is a remove method, used to remove an entity bean instance. In other words, when you invoke the remove method on an entity bean, you remove the bean and the underlying record in the database. Remove methods are defined in all the interfaces. For instance, to remove a bean instance via the local home interface, you can invoke a remove method that takes instance's primary key as the parameter. To remove a bean instance via the local interface, you can invoked the remove method for the instance you want to remove. Both approaches are shown below; the session bean's method deleteViaHome deletes an instance of the Product bean via its local home interface, while deleteViaBusiness delete a Product bean instance via the local interface:

/**
 * ...
 *
 * @ejbgen:ejb-local-ref link="Product"
 */
public class SomeSession extends GenericSessionBean implements SessionBean
{
   ...

    /**
     * @ejbgen:local-method
     */
    public void deleteViaHome(myBeans.ProductBeanPK thePk)
    {
       try {        
          javax.naming.Context ic = new InitialContext();
          ProductHome productHome = (ProductHome)ic.lookup("java:comp/env/ejb/Product");
          productHome.remove(thePk);
       }
       catch(NamingException ne) {
          ...
       }
       catch(RemoveException re) {
          ...
       }
    }

   /**
     * @ejbgen:local-method
     */
    public void deleteViaBusiness(myBeans.ProductBeanPK thePk)
    {
       try {        
          javax.naming.Context ic = new InitialContext();
          ProductHome productHome = (ProductHome)ic.lookup("java:comp/env/ejb/Product");
          Product theProduct = productHome.findByPrimaryKey(thePk);
          theProduct.remove();
       }
       catch(NamingException ne) {
          ...
       }
       catch(FinderException ne) {
          ...
       }       
       catch(RemoveException re) {
          ...
       }
    }

   ...
}

Callback Methods


Every entity bean must implement the javax.ejb.EntityBean interface. This interface defines callback methods that are called by the EJB container at specific times. The callback methods are setEntityContext, unsetEntityContext, ejbActivate, ejbPassivate, ejbLoad, ejbStore, and ejbRemove. When you define an entity bean from scratch or via a database table, it will extend weblogic.ejb.GenericEntityBean, which contains empty implementations of these callback methods. In other words, you will only need to define these methods if you need to override the empty implementation. If you import an entity bean, these callback methods will probably be implemented directly in the bean's ejb file.

For more details about the callback methods and their role in the interaction between the entity bean and the EJB container, see The Life Cycle of an Entity Bean.




Automatic Primary Key Generation


In WebLogic it is possible to automatically generate a primary key to be used when creating a new CMP entity bean instead of providing primary key values. You can auto-generate primary keys in various vendor-specific ways - using Oracle, SQLServer, or SQLServer2000 - or you can use a vendor-neutral named sequence table. In all cases auto-generated primary keys are of type Integer or Long.

The topics in this section are:

  • Primary Key Generation Using Oracle's Sequence
  • Primary Key Generation Using SQL Server's IDENTITY
  • Primary Key Generation Using a Named Sequence Table
  • Defining the CMP Entity Bean


Primary Key Generation Using Oracle's Sequence


Oracle provides the 'sequence' utility to automatically generate unique primary keys. To use this utility to auto-generate primary keys for a CMP entity bean, you must create a sequence table and use the ejbgen:automatic-key-generation tag to point to this table.

In your Oracle database, you must create a sequence table that will create the primary keys, like is shown in the following example:

create sequence myOracleSequence
start with 1 
nomaxvalue; 

This creates a sequences of primary key, starting with 1, followed by 2, 3, and so forth. The sequence table in the example uses the default increment 1, but you can change this by specifying the increment keyword, such as increment by 3. When you do the latter, you must specify the exact same value in the cache-size attribute of the ejbgen:automatic-key-generation tag:

@ejbgen:automatic-key-generation type="Oracle" name="myOracleSequence" cache-size="3" 

If you have specified automatic table creation in the CMP bean's project settings, the sequence table will be created automatically when the entity bean is deployed. For more information, see @ejbgen:jar-settings Annotation. For more information on the definition of a CMP entity bean, see below.


Primary Key Generation Using SQL Server's IDENTITY


In SQL Server (2000) you can use the 'IDENTITY' keyword to indicate that a primary-key needs to be auto-generated. The following example shows a common scenario where the first primary key value is 1, and the increment is 1:

CREATE TABLE Customer (Customer_ID int IDENTITY(1,1), FirstName varchar(30) LastName varchar(30))

In the CMP entity bean definition you need to specify SQLServer(2000) as the type of automatic key generator you are using. You can also provide a cache size:

@ejbgen:automatic-key-generation type="SQLServer"

If you have specified automatic table creation in the CMP bean's project settings, the sequence table will be created automatically when the entity bean is deployed. For more information, see @ejbgen:jar-settings Annotation. For more information on the definition of a CMP entity bean, see below.

Note. The SQLServer2000 option is the same as SQLServer, except that SQLServer uses @@IDENTITY column to get the generated key value and SQLServer2000 uses the SCOPE_IDENTITY() function instead.


Primary Key Generation Using a Named Sequence Table


A named sequence table is similar to the Oracle sequence functionality in that a dedicated table is used to generate primary keys. However, the named sequence table approach is vendor-neutral. To auto-generate primary keys this way, create a named sequence table using the two SQL statements shown in the example:

CREATE Table MyNamedSequence (SEQUENCE number);

INSERT into MyNamedSequence VALUES (0);

In the CMP entity bean definition you need to specify the named sequence table as the type of automatic key generator you are using. You can also provide a cache size:

@ejbgen:automatic-key-generation name="MySequence" type="MyNamedSequenceTable" cache-size="100" 

If you have specified automatic table creation in the CMP bean's project settings, the sequence table will be created automatically when the entity bean is deployed. For more information, see @ejbgen:jar-settings Annotation. For more information on the definition of a CMP entity bean, see the next section.

Note. When you specify a cache-size for a named sequence table, a series of unique values are reserved for entity bean creation. When a new cache is necessary, a second series of unique values is reserved, under the assumption that the first series of unique values was entirely used. This guarantees that primary key values are always unique, although it leaves open the possibility that primary key values are not necessarily sequential. For instance, when the first series of values is 10...20, the second series of values is 21-30, even if not all values in the first series were actually used to create entity beans.


Defining the CMP Entity Bean


When defining a CMP entity bean that uses one of the primary key generators, you point to the name of the primary key generator table to obtain primary keys, using the ejbgen:automatic-key-generation tag. Also, you must define a primary key field of type Integer or Long, to set and get the auto-generated primary key. However, the ejbCreate method does not take a primary key value as an argument. Instead the EJB container adds the correct primary key to the entity bean record.

The following example shows what the entity bean might look like. Notice that the bean uses the named sequence option describe above, and that ejbCreate method does not take a primary key:
 /**
 * @ejbgen:automatic-key-generation name="MyNamedSequence" type="NamedSequenceTable"
 cache-size="100"
 * 
 * @ejbgen:entity prim-key-class="java.lang.Integer"
 *   ejb-name = "Customer"
 *   data-source-name = "MyCustomerDataSource"
 *   table-name = "customer"
 *   abstract-schema-name = "Customer"
 *
 * ...
 */
abstract public class Customer extends GenericEntityBean implements EntityBean
{
    ...

    /**
     * @ejbgen:cmp-field primkey-field="true" column="Customer_ID"
     * @ejbgen:local-method
     */
    public abstract Integer getCustomer_ID();

    /**
     * @ejbgen:local-method
     */
    public abstract void setCustomer_ID(Integer arg);

    public java.lang.Integer ejbCreate(java.lang.String LastName, java.lang.String FirstName)
    {
      setLastName(LastName);
      setFirstName(FirstName);

      return null; // FIXME return PK value 
    }
}




Entity Relationships


Entity relationships are used to model real-world dependencies between business concepts with CMP entity beans. This topics gives an overview of the seven relationship types, and for each of these relationships describes implementation details in the EJBs and the underlying database tables. For more detailed information, see your favorite J2EE documentation.

The topics in this section are:

  • One-to-One, Unidirectional
  • One-to-One, Bidirectional
  • One-to-Many, Unidirectional
  • One-to-Many, Bidirectional
  • Many-to-One, Unidirectional
  • Many-to-Many, Unidirectional
  • Many-to-Many, Bidirectional


One-to-One, Unidirectional


In a one-to-one unidirectional relationship, object A relates to object B. In addition, given object A you can find a reference to object B, but not the other way around. An example of such a relationship is between a concertgoer and a ticket, assuming the perspective of the ticket counter. Each concertgoer requires exactly one ticket, and the concertgoer will have a reference to his/her ticket. However, given a ticket you don't know the concertgoer. That is, if a lost ticket is returned to the ticket counter, it is not possible to trace it back to the concertgoer.

The Concertgoer EJB will have a CMR field to set and get a reference to a Ticket object. In contrast, there is no reference from the Ticket to the Concertgoer, meaning that there is no direct way to find out if a particular ticket has been assigned to a concertgoer or not and if it has, who the concertgoer is. (To find this out, you would have to run a query on the Concertgoer EJBs and check each referenced ticket .)

In this particular example, Ticket objects are probably created independently of Concertgoer objects, and the CMR set method is used to associate the Concertgoer with the Ticket. Also, when the concertgoer returns the ticket (and removes himself from the ticket counter database), the Ticket object may not be deleted because it can be resold. When the one-to-one unidirectional relationship is more dependent, as between a Customer and his/her Address, the Customer EJB may have an setAddress business method, which creates a new Address object first, and then uses the CMR set method to set the reference, as is shown in the following code snippet:

   public void setAddress(String street, String apt, String city, String state, String zip) throws CreateException
   {
       Address currentAddress = this.getAddress( );
       if (currentAddress == null) {
           // Customer's current address not known.	
           newAddress = addressHome.create(street, apt, city, state, zip);
           setAddress(newAddress);
       } 
       else {
           // Update customer's current address. 
           currentAddress.setStreet(street);
           currentAddress.setApt(apt);
           currentAddress.setCity(city);
           currentAddress.setState(state);
           currentAddress.setZip(zip);
       }
   }

Notice that first the CMR get method is used to get the reference to the current address. if the address is not known, a new address object is created after which the reference is set. If there is already a reference to an address, the address object is updated to reflect the new address.

When a customer is removed from the database, the home address can likely be removed as well. To do so, you can specify a cascade delete for this entity relationship, which automatically removes the home address when the customer is removed. For more information, see the @ejbgen:relation Annotation.

With respect to persistent storage of this relationship, one table will have the foreign key column information, that is hold the a copy of the primary key of the other EJB. Typically the Concertgoer table will have an 'Ticket_Index' foreign-key column holding the primary key value of the address (assuming that the Ticket EJB defines only one primary key field; if there are multiple primary key columns, there are multiple foreign key columns holding these values). It is, however, also possible that the Ticket table holds the primary key value of the Concertgoer. Regardless of the implementation in the database table, the EJB container will ensure that the relationship is correctly represented.


One-to-One, Bidirectional


In a one-to-one bidirectional relationship, object A relates to object B and both reference each other. An example of such a relationship is between a concertgoer and a creditcard, again assuming the perspective of the ticket counter. Each concertgoer has only one credit card (to purchase a ticket), and if a credit card is inadvertently left behind at the ticket counter, it can be returned to the owner.

The Concertgoer EJB will have a CMR field to set and get a reference to a CreditCard object. In addition, the CreditCard object will have a CMR field to set and get a reference to a Concertgoer object. Also, the bidirectionality of this relationship is ensured by the EJB container. That is, when you use the Concertgoer's CMR set method to set a reference to a CreditCard object, the CMR field of the CreditCard object is automatically updated to hold a reference to this Concertgoer. Similarly, when you change or remove a reference in one object, this change is automatically applied to the other object. As far as creating and deleting the object a CMR field references, similar design considerations apply as discussed above for one-to-one unidirectional relationships. With respect to creating a new creditcard for a concertgoer, it is possible that the Concertgoer EJB has a business method setCreditCard, which creates a new creditcard record and then sets the reference, similar to the setAddress method shown above. If on the other hand the CreditCard EJB defines a create method that creates the CreditCard object and sets the reference to the Concertgoer object, the reference must be set in the ejbPostCreate step. An example of this is shown below.

With respect to persistent storage of this relationship, there is again quite some flexibility how this is implemented in the database tables. One of the possibilities is that only the ConcertGoer table has a foreign key column holding the primary key value of a creditcard. There are other possibilities as well. Regardless of the implementation in the database table, the EJB container will ensure that the relationship is correctly represented.


One-to-Many, Unidirectional


In a one-to-many unidirectional relationship, object A relates to many objects B, there are references from object A to all objects B, but not the other way around. An example of such a relationship is between a concertgoer and CDs purchased after the concert. A concertgoer can purchase many CDs, but for a purchased CD, again inadvertently lost and found, it is not possible to trace it back to the concertgoer who made the purchase.

The Concertgoer EJB will have a CMR field to set and get a Collection/Set of references to CD objects. In contrast, there is no CMR field in the CD object. The choice of java.util.Collection versus java.util.Set depends on whether from a design perspective it makes sense to have a collection with potentially duplicate references to the same object, or to have a set without duplicate references.

In this particular example, Concertgoer objects are probably created independently of CD objects, and a new reference is added to the CMR field uses the Collection/Set's add method, while a reference is deleted without deleting the CD object using the Collection/Set's remove method. When the relationship is more dependent, as between a Band and its Recordings, the Band EJB may have an addRecording business method, which creates a new Recording object first, and then adds it to the collection, as is shown in the following code snippet:

   public void addRecording(String recording) throws CreateException
   {
      Recording album = recordingHome.create(getBandName(), recording);
      Collection recordings = getRecordings();
      if(album != null) {
         recordings.add(album);
      }
    }

Notice that this method first creates the album, then uses the CMR get method to obtain a collection of the current recordings of the band, and then adds the new recording to the collection. Without the last step the recording would be created, but would not be referenced by the band.

When the Band object is deleted from the database, it might or might not make sense to cascade delete its recordings, depending on the real-world scenario you are representing.

With respect to persistent storage of this relationship, the only possible implementation is for the CD table to have a foreign key column holding the primary value of the concertgoer. As you might notice, the model and the actual implementation are reversed; the EJB container again ensures that the relationship is correctly represented.

Note. WebLogic at present doesn't support the use of a join table to implement one-to-many relationships.


One-to-Many, Bidirectional


In a one-to-many bidirectional relationship, object A relates to many objects B, there are references from object A to all objects B, and each object B references object A. An example of such a relationship is between a concertgoer and a creditcard, assuming the perspective of the concertgoer. Each concertgoer can have many credit cards, and if a credit card is inadvertently lost, it can be returned to the owner. Notice that this is the second example of a relationship between a concertgoer and creditcard. Above a one-to-one bidirectional relationship was defined, assuming the perspective of the ticket counter instead of the concertgoer.

Note. Realize that one-to-many bidirectional relationships and many-to-one bidirectional relationships are conceptually identical and are therefore listed as one type of relationship.

The Concertgoer EJB will have a CMR field to set and get a Collection/Set of references to CreditCard objects. The CreditCard object will have a CMR field to set and get a reference to a ConcertGoer object. Again, the bidirectionality of this relationship is ensured by the EJB container. That is, when you set/add the reference to one of the EJBs, the reference is automatically updated for the other EJB. As far as creating and deleting the object a CMR field references, similar design considerations apply as discussed above.

With respect to persistent storage of this relationship, the only possible implementation is for the CreditCard table to have a foreign key column holding the primary value of the concertgoer.

Note. WebLogic at present doesn't support the use of a join table to implement one-to-many relationships.


Many-to-One, Unidirectional


In a many-to-one unidirectional relationship, many objects A relate to one object B, there is a reference from each object A to object B, but not the other way around. An example of such a relationship is between a concert and a venue, assuming the perspective of a concertgoer. There are many different concerts at the same venue but the concertgoer is probably less concerned to know the concerts given the venue. However, if the latter is a business requirement, you will model this as a one-to-many (venue-to-concerts) bidirectional relationship.

The Concert EJB will have a CMR field to set and get a reference to a Venue object. In contrast, the Venue object will not have a CMR field. When a new concert is scheduled, the venue likely needs to be known at this time. In other words, when you create a Concert object, the reference to the Venue object should be set as part of the create procedure, as is shown in the following example:

abstract public class ConcertBean extends GenericEntityBean implements EntityBean
{
   ...

   public Integer ejbCreate(String bandName, Venue theVenue) {
       setBandName(bandName);
       return null;
   }
	
   public void ejbPostCreate(String bandName, Venue theVenue) {
       setVenue(theVenue);
   }

   ...

Notice that ejbCreate sets the name of the performing band, while the reference to the Venue object is set in the corresponding ejbPostCreate method. References must by design always be set in the ejbPostCreate method, because the primary key(s) needed to set the reference may not be available yet until after creation of the object.

Cascade deletions will most likely not make sense for this relationship. That is, removing one concert should not lead to the destruction of the venue, as many other concerts are scheduled for this venue.

With respect to persistent storage of this relationship, the only possible implementation is for the Concert table to have a foreign key column holding the primary value of the venue.

Note. WebLogic at present doesn't support the use of a join table to implement one-to-many relationships.


Many-to-Many, Unidirectional


In a many-to-many unidirectional relationship, object A relates to many objects B, object B relates to many objects A, there are references from each object A to its objects B, but not the other way around. An example of such a relationship is between concertgoers and concerts. A concertgoer will attend many concerts, each concerts will attract many concertgoers, given a concertgoer you might want to know the concerts he/she attended, but given a concert you likely don't want to know the particular concertgoers that were attending it.

The Concertgoers EJB will have a CMR field to set and get a collection/set of references to Concert objects. In contrast, the Concert object will not have a CMR field. As far as manipulating the CMR field, and creating and deleting the objects the CMR field references, similar design considerations apply as discussed above. Cascade deletions typically do not make sense for many-to-many relationships.

With respect to persistent storage of this relationship, a join table is used. Each record in a join table has two foreign-key columns, one holding the primary key value of a concertgoer and the other holding the primary key value of the concert (again assuming that both EJBs are defined to have one unique primary key field).


Many-to-Many, Bidirectional


In a many-to-many bidirectional relationship, object A relates to many objects B, object B relates to many objects A, there are references from each object A to its objects B as well as references from each object B to its objects A. An example of such a relationship is between a passenger and a flight. A passenger can take multiple flights, a flight is typically booked by multiple passengers, given a passenger you want to know the flights, and for a flight you want to know exactly which passengers should be on the airplane.

The Passenger EJB will have a CMR field to set and get a collection/set of references to Flight objects. The Flight EJB will have a CMR field to set and get a collection/set of references to Passenger objects. As far as manipulating the CMR field, and creating and deleting the objects the CMR field references, similar design considerations apply as discussed above. In this particular example it is possible that a passenger books a flight for several passengers at the same time. You can use the Collection/Set's addAll method to add multiple references. Also notice that bidirectionality is again assured by the EJB container, and that cascade deletions typically do not make sense for many-to-many relationships.

With respect to persistent storage of this relationship, a join table is used. Each record in a join table has two foreign-key columns, one holding the primary key value of a concertgoer and the other holding the primary key value of the concert (again assuming that both EJBs are defined to have one unique primary key field).



Be the first one to comment on this page.




  Weblogic Tutorial eBooks

No eBooks on Weblogic could be found as of now.

 
 Weblogic Tutorial FAQs
More Links » »
 
 Weblogic Tutorial Interview Questions
More Links » »
 
 Weblogic Tutorial Articles

No Weblogic Articles could be found as of now.

 
 Weblogic Tutorial News

No News on Weblogic could be found as of now.

 
 Weblogic Tutorial Jobs

No Weblogic Articles could be found as of now.


Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • connotea
  • del.icio.us
  • De.lirio.us
  • digg
  • Fark
  • feedmelinks
  • Furl
  • LinkaGoGo
  • Ma.gnolia
  • NewsVine
  • Netvouz
  • RawSugar
  • Reddit
  • scuttle
  • Shadows
  • Simpy
  • Smarking
  • Spurl
  • TailRank
  • Wists
  • YahooMyWeb

Previoushome Next

Keywords: Developing Enterprise JavaBeans, WEBLOGIC, WebLogic, WebLogic tutorials, WebLogic tutorial pdf, history of WebLogic, How To Deploy An Application Using WebLogic , learn WebLogic

HTML Quizzes
HTML Quiz
XHTML Quiz
CSS Quiz
TCP/IP Quiz
CSS 1.0 Quiz
CSS 2.0 Quiz
HLML Quiz
XML Quizzes
XML Quiz
XSL Quiz
XSLT Quiz
DTD Quiz
Schema Quiz
XForms Quiz
XSL-FO Quiz
XML DOM Quiz
XLink Quiz
XQuery Quiz
XPath Quiz
XPointer Quiz
RDF Quiz
SOAP Quiz
WSDL Quiz
RSS Quiz
WAP Quiz
Web Services Quiz
Browser Scripting Quizzes
JavaScript Quiz
VBScript Quiz
DHTML Quiz
HTML DOM Quiz
WMLScript Quiz
E4X Quiz
Server Scripting Quizzes
ASP Quiz
PERL Quiz
SQL Quiz
ADO Quiz
CVS Quiz
Python Quiz
Apple Script Quiz
PL/SQL Quiz
SQL Server Quiz
PHP Quiz
.NET (dotnet) Quizzes
Microsoft.Net Quiz
ASP.Net Quiz
.Net Mobile Quiz
C# : C Sharp Quiz
ADO.NET Quiz
VB.NET Quiz
VC++ Quiz
Multimedia Quizzes
SVG Quiz
Flash Quiz
Media Quiz
SMIL Quiz
Photoshop Quiz
Gimp Quiz
Matlab Quiz
Gnuplot Programming Quiz
GIF Animation Quiz
Scientific Visualization Quiz
Graphics Quiz
Web Building Quizzes
Web Browsers Quiz
Web Hosting Quiz
W3C Quiz
Web Building Quiz
Web Quality Quiz
Web Semantic Quiz
Web Careers Quiz
Weblogic Quiz
SEO Quiz
Web Site Hosting Quiz
Domain Name Quiz
Java Quizzes
Java Quiz
JSP Quiz
Servlets Quiz
Struts Quiz
EJB Quiz
JMS Quiz
JMX Quiz
Eclipse Quiz
J2ME Quiz
JBOSS Quiz
Programming Langauges Quizzes
C Quiz
C++ Quiz
Visual Basic Quiz
Data Structures Using C Quiz
Cobol Quiz
Assembly Language Quiz
Mainframe Quiz
Forth Programming Quiz
Lisp Programming Quiz
Pascal Quiz
Delphi Quiz
Fortran Quiz
OOPs Quiz
Data Warehousing Quiz
CGI Programming Quiz
Emacs Quiz
Gnome Quiz
ILU Quiz
Soft Skills Quizzes
Communication Skills Quiz
Time Management Quiz
Project Management Quiz
Team Work Quiz
Leadership Skills Quiz
Corporate Communication Quiz
Negotiation Skills Quiz
Database Quizzes
Oracle Quiz
MySQL Quiz
Operating System Quizzes
BSD Quiz
Symbian Quiz
Unix Quiz
Internet Quiz
IP-Masquerading Quiz
IPC Quiz
MIDI Quiz
Software Testing Quizzes
Testing Quiz
Firewalls Quiz
SAP Module Quizzes
ERP Quiz
ABAP Quiz
Business Warehousing Quiz
SAP Basis Quiz
Material Management Quiz
Sales & Distribution Quiz
Human Resource Quiz
Netweaver Quiz
Customer Relationship Management Quiz
Production and Planning Quiz
Networking Programming Quizzes
Corba Quiz
Networking Quiz
Microsoft Office Quizzes
Microsoft Word Quiz
Microsoft Outlook Quiz
Microsoft PowerPoint Quiz
Microsoft Publisher Quiz
Microsoft Excel Quiz
Microsoft Front Page Quiz
Microsoft InfoPath Quiz
Microsoft Access Quiz
Accounting Quizzes
Financial Accounting Quiz
Managerial Accounting Quiz
Testimonials | Contact Us | Link to Us | Site Map
Copyright ? 2008. Academic Tutorials.com. All rights reserved Privacy Policies | About Us
Our Portals : Academic Tutorials | Best eBooksworld | Beyond Stats | City Details | Interview Questions | Discussions World | Excellent Mobiles | Free Bangalore | Give Me The Code | Gog Logo | Indian Free Ads | Jobs Assist | New Interview Questions | One Stop FAQs | One Stop GATE | One Stop GRE | One Stop IAS | One Stop MBA | One Stop SAP | One Stop Testing | Webhosting in India | Dedicated Server in India | Sirf Dosti | Source Codes World | Tasty Food | Tech Archive | Testing Interview Questions | Tests World | The Galz | Top Masala | Vyom | Vyom eBooks | Vyom International | Vyom Links | Vyoms | Vyom World | Important Websites
Copyright ? 2003-2024 Vyom Technosoft Pvt. Ltd., All Rights Reserved.