# 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
- Defining a Basic Entity Bean
- Removing an Entity Bean Instance
- Callback Methods

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

Related Topics

The Life Cycle of an Entity Bean

@ejbgen:file-generation Annotation

@ejbgen:local-method Annotation

How Do I: Add a Create Method to an Entity Bean?