Previous Next vertical dots separating previous/next from contents/index/pdf

Defining an Entity Bean

This topic discusses how to create an entity bean and what an entity bean minimally must contain. Furthermore, it describes how to remove a bean instance, and discusses the various interfaces extended by an entity bean. This topic contains the following sections:


Creating an Entity Bean

The WebLogic Entity Bean wizard makes it easy to start creating an entity bean from scratch. If you are designing a new entity bean in a WebLogic EJB project, using the wizard will create basic entity bean code from a template. To use the wizard, in Workshop for WebLogic, right-click your WebLogic EJB project folder, point to New, then click WebLogic Entity Bean.

For more information on creating new beans, see Tutorial: Building Enterprise JavaBeans. When you create a new entity bean, by default the local interfaces and various other defaults are defined. For more details, see @FileGeneration Annotation.

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.

Automatic Table Creation

When you are developing a new entity bean, you can make iterative development easier by enabling automatic table creation. You can have the server create the table when it is not present, or 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 in the Properties dialog for the WebLogic EJB project. In that dialog, in the left pane, click WebLogic EJB; in the right pane choose a value from th "create tables" dropdown. The default setting is CREATE_ONLY. To recreate a table if the definition of the entity bean does not match the table specification, use DROP_AND_CREATE. For more information regarding the possible settings, see @JarSettings Annotation.

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

Defining a Basic Entity Bean

The following 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. This entity bean allows you to add a new product, find a product using its primary key, and get and set its CMP field values.

package myBeans;

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

@Entity(ejbName = "Product", 
        dataSourceName = "samplesDataSource", 
        tableName = "product", 
        abstractSchemaName = "Product", 
        primKeyClass = "String")
@AutomaticKeyGeneration(cacheSize = "1", 
        name = "NamedSequence", 
        type = AutomaticKeyGeneration.AutomaticKeyGenerationType.SEQUENCE_TABLE)
@JndiName(local = "ejb.ProductLocalHome")
@FileGeneration(localClass = Constants.Bool.TRUE, 
        localClassName = "Product", 
        localHome = Constants.Bool.TRUE, 
        localHomeName = "ProductHome", 
        remoteClass = Constants.Bool.FALSE, 
        remoteHome = Constants.Bool.FALSE, 
        remoteHomeName = "ProductRemoteHome", 
        remoteClassName = "ProductRemote", 
        valueClass = Constants.Bool.FALSE, 
        valueClassName = "ProductValue", 
        pkClass = Constants.Bool.TRUE)
abstract public class ProductBean 
    extends GenericEntityBean 
    implements EntityBean {
    @CmpField(column = "Name", 
            primkeyField = Constants.Bool.TRUE)
    @LocalMethod()
    public abstract String getName();

    @LocalMethod()
    public abstract void setName(String arg);

    @CmpField(column = "Price")
    @LocalMethod()
    public abstract double getPrice();

    @LocalMethod()
    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 Workshop for 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. Workshop for WebLogic interprets ejbgen annotations in your source code to generate these files. For example, the @FileGeneration annotation specifies the names of the local home and business interface for the ProductBean. The @LocalMethod annotations on the accessor methods specify that these methods are defined in the local business interface.

You can view the generated JAVA files in Resource view. In that view, expand the .apt_src folder to view folders corresponding to your source packages. You'll find the generated files in these folders. For the ProductBean, you'd find a Product interface that extends EJBLocalObject and a ProductHome interface that extends EJBLocalHome. You can view the CLASS files compiled from the generated files (again, in Resource view) by expanding the project's build folder.

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.

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. These interfaces include:

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 interfaces is a remove method you can use to remove an entity bean instance. In other words, when you invoke the remove method on an entity bean, you remove the bean and its 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 invoke 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:

package myBeans;

import javax.ejb.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import weblogic.ejb.*;
import weblogic.ejbgen.*;

@EjbLocalRefs( { @EjbLocalRef(link = "Product") })
@Session(ejbName = "SomeSession")
@JndiName(remote = "ejb.SomeSessionRemoteHome")
@FileGeneration(remoteClass = Constants.Bool.TRUE, 
        remoteHome = Constants.Bool.TRUE, 
        localClass = Constants.Bool.TRUE, 
        localHome = Constants.Bool.TRUE, 
        localClassName = "SomeSessionLocal", 
        localHomeName = "SomeSessionLocalHome")
public class SomeSession extends GenericSessionBean 
    implements SessionBean {
    private static final long serialVersionUID = 1L;

    @LocalMethod()
    public void deleteViaHome(String thePk) {
        try {
            javax.naming.Context ic = new InitialContext();
            ProductHome productHome = (ProductHome) ic
                    .lookup("java:comp/env/ejb/Product");
            productHome.remove(thePk);
        } catch (NamingException ne) {
            // Exception handling code.
        } catch (RemoveException re) {
            // Exception handling code.
        }
    }

    @LocalMethod()
    public void deleteViaBusiness(String 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) {
            // Exception handling code.
        } catch (FinderException ne) {
            // Exception handling code.
        } catch (RemoveException re) {
            // Exception handling code.
        }
    }

    public void ejbCreate() {
        // Bean initialization code here.
    }

}

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 source 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.

Related Topics

The Life Cycle of an Entity Bean

@FileGeneration Annotation

@LocalMethod Annotation

 

Skip navigation bar   Back to Top