Skip Headers
NetBeans Developing Applications with NetBeans IDE
Release 7.4

E40142-08
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

15 Developing with Enterprise Beans

This chapter describes how to use the IDE to implement Enterprise JavaBeans (EJB) technology in applications.

This chapter contains the following sections:

15.1 About Developing with Enterprise Beans

Written in the Java programming language, an enterprise bean 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. In an inventory control application, for example, the enterprise beans might implement the business logic in methods called checkInventoryLevel and orderProduct. By invoking these methods, remote clients can access the inventory services the application provides. See Section 15.3, "Creating an Enterprise Bean."

Enterprise beans provide the following advantages when developing large, distributed applications:

You can develop the following types of enterprise beans:

For additional information see Section 15.2.1, "How to Create an EJB Module Project," and Section 15.1, "About Developing with Enterprise Beans."

15.2 Creating an EJB Module Project

The following steps summarize enterprise development tasks.

  1. Create the EJB module project.

    • Register a Java EE application server. You cannot deploy EJB modules to the Tomcat server.

    • Create the project for the EJB module.

    • Add the EJB module to an enterprise application.

  2. Code the enterprise beans.

    • Create the enterprise beans.

    • Access the database.

      For Java EE 5 applications, use Java Persistence.

      If you want to use a database schema, make sure the database schema file exists in your project's conf folder.

    • Call enterprise beans from web application modules and other enterprise beans.

    • Add business methods to your enterprise beans.

    • Add select methods and finder methods to your entity beans.

    • Use server resources like databases and JMS messages.

  3. Configure the application.

    • Edit the EJB module's deployment descriptors.

    • Configure container-managed relationships between enterprise beans.

  4. Build the project.

    • Set the project as the main project and choose Run > Build Main Project (F11) from the main menu or right-click the project node in the Projects window and choose Build.

  5. Deploy the module.

    1. For stand-alone EJB modules, right-click the EJB module's project node and choose Run.

    2. For EJB modules that are part of an enterprise application, right-click the enterprise application and choose Run.

15.2.1 How to Create an EJB Module Project

The IDE provides wizards to help you create EJB module projects for EJB 3.1 enterprise beans (EJB 2.1 is a mandatory part of the EJB 3.1 specification). The wizard can also help you create an EJB module if you already have existing source code.

To create an EJB module project:

  1. Choose File > New Project (Ctrl+Shift+N) from the main window.

  2. From the Java EE category, select one of the following project templates:

  3. Follow the steps in the rest of the wizard.

For related information see Section 5.2.3, "Creating Standard Projects," and Section 11.2.1, "How to Create a Web Application Project."

Note:

For standard EJB module projects, the IDE does not support J2EE 1.3 EJB modules and automatically updates the version number of your EJB module's ejb-jar.xml to 1.4. The J2EE 1.4 specification is fully backward-compatible, so upgrading the specification level does not change the behavior of your code.

When you import an individual EJB module into a standard project, the module can have any folder structure. When importing an entire application using the Enterprise Application with Existing Sources template, the project's folder structure must adhere to the application structure shown in Figure 15-1.

Figure 15-1 J2EE Blueprint Conventions for Application Structures

J2EE blueprint conventions for apps

15.3 Creating an Enterprise Bean

The IDE provides templates for creating session beans, message-driven beans, entity beans, and legacy CMP entity beans.

15.3.1 How to Create Enterprise Beans

Enterprise Java Beans can be added to EJB module projects.

To create enterprise beans:

  1. In the Projects window, select any existing EJB module project. See Section 15.2.1, "How to Create an EJB Module Project."

  2. Choose File > New from the main menu.The New File wizard opens.

  3. From the Enterprise JavaBeans category, select one of the following EJB templates:

    • Session Bean

    • Timer Session Bean

    • Message-Driven Bean

    • Session Beans for Entity Classes

  4. Follow the directions in the rest of the wizard.

When you create an enterprise bean, the IDE does the following:

  • Java EE projects:

    • Adds a node for the enterprise bean under the project's Enterprise Beans node. This node can contain nodes for bean methods and fields.

    • Creates the bean class and the interfaces under the Source Packages node

    • Opens the bean class in the Source Editor

  • J2EE 1.4 projects:

    • Adds a node for the enterprise bean under the project's Enterprise Beans node. This node can contain nodes for bean methods and fields.

    • Updates the deployment descriptors for the EJB module and the Enterprise Application module that contains the EJB module. If your target server is the GlassFish server, the IDE also configures the server-specific deployment descriptors. For all other application servers, you have to write the server-specific deployment descriptors yourself.

    • Opens the bean class in the Source Editor

For more information on enterprise projects and beans, see Section 11.2, "Creating Web Application Projects," and Section 13.5.1, "How to Build an Enterprise Application Project and Sub-Projects."

15.3.2 How to Generate Session Beans for Entity Classes

The IDE provides a wizard to generate session beans for entity classes. In the wizard choose the entity classes that require session beans. The wizard creates a session facade as well as the selected interfaces for the selected entity class.

To generate session beans from entity classes:

  1. Right-click the module project node in the Projects window and choose New > Other.

  2. In the New File wizard, go to the Persistence category and select Session Beans for Entity Classes. See Section 16.1, "About Developing with Java Persistence."

  3. Select any entity classes from the list in the left pane and click the Add button. Any referenced entity classes are automatically added to the list in the right pane. The IDE generates session beans for each entity class listed in the right pane.

    Deselect Include Referenced Classes if you do not want session beans created for referenced classes.

  4. Click Next.

  5. Select the location where you want to save the session beans.

  6. Select an existing package from the Package drop-down menu or type the name of a new package.

  7. Select the session facade interfaces that you want the wizard to generate.

  8. Click Finish.

When you click Finish, the IDE creates session beans for each of the entity classes you specified in the wizard.

15.3.3 How to Define a Business Method for an Enterprise Bean

A business method is a method inside an enterprise bean that performs some function and can be called from outside the bean. Business methods are written in the bean class and exposed through local or remote interfaces. If a business method is meant to be called by beans and clients that are running in the same JVM (on the same server), they are registered in the bean's local interface. If the method is meant to be called from a remote client, it is registered in the bean's remote interface.

A session bean's business methods typically define tasks that the bean performs for clients. They are not necessarily associated with data in a database.

In EJB 2.1 programming, an entity bean represents a persistent business object whose data is stored in a database. The bean adds behavior specific to that data. Therefore, an entity bean's business methods are typically accessor and mutator methods that enable you to read and update information in a database that represents a business concept. Entity bean business methods are almost always local methods, since remote clients should only access an entity bean through a facade session bean.

Business Methods in the IDE

When you create an EJB 2.1 enterprise bean (J2EE 1.4), the IDE creates a special BeanInterfaceBusiness interface in which it registers business methods. The bean interface extends the Business interface and the bean class implements both the bean interface and the RemoteBusiness interface.

The advantage of this approach is that it lets you separate the business logic from implementation logic, and that it lets you check at compile-time that your bean implements the given interfaces. If you want to register business methods directly in the bean's interfaces, delete the Business interface files. Then edit the bean interface to not extend the Business interface and edit the bean class to not implement the Business interface.

When working with EJB 3.0 or EJB 3.1 enterprise beans, there is no need for a separate Business interface because the enterprise beans are regular Java objects and therefore have only the remote and local interfaces.

To define a business method for an enterprise bean:

  1. Open the bean class in the Source Editor.

  2. Right-click anywhere in the Source Editor and choose Insert Code > Add Business Method.

  3. In the Add Business Method dialog box, define the method signature:

    1. Name the method.

    2. Specify the return type.

    3. Specify the method parameters in the Parameters tab.

    4. Specify the exceptions that the method throws in the Exceptions tab.

  4. Specify whether to add the business method to the local interface, remote interface, or both.

  5. Click OK to create the method.

  6. The IDE adds the method signature to the interfaces and the method body to the bean class.

  7. Edit your new business method.

You can also just code a regular method and then click the IDE hint in the left margin and choose an interface from the popup menu.

Note:

When the IDE adds a business method to an enterprise bean, it does not save the bean class or the bean interfaces. Only when you compile or save the class is the new method saved to disk.

For related information see Section 15.6.4, "How to Define a Finder Method for an Entity Bean," and Section 15.6.8, "How to View, Edit or Delete Existing Select Methods."

15.3.4 How to Send JMS Messages

A Java Message Service (JMS) message is an object that communicates information between JMS clients. The message is sent from one client to a second client that listens for messages through a JMS destination on an application server. In the IDE, you can automatically generate code to send a JMS message to any message-driven bean in an open project.

To send a JMS message:

  1. (Optional) Create a service locator class to handle getting the reference to the database. See Section 15.3.5, "How to Use a Service Locator."

  2. Open the Java file from which you want to send the JMS message. The file must be in an EJB module project or a standard web application project. You cannot generate lookup code in a free-form web application project. See Section 15.3.4, "How to Send JMS Messages," and Section 22.3.9, "How to Set up a JMS Resource."

  3. In the Source Editor, right-click in the file and choose Insert Code > Send JMS Message.

  4. Select the message-driven bean that is the destination for the message. You can switch between open projects using the Project drop-down menu.

  5. Under Service Locator Strategy, specify whether to generate inline lookup code or use an existing service locator. Click Browse to search for the service locator class name.

  6. Click OK. The IDE creates two methods:

    • createJMSMessageForNewMessageDestination. The method that creates the message that is sent. You should implement your business logic in this method.

    • sendJMSMessageToNewMessageDestination. The method that handles the message you created in the method above. You should not modify this message.

      The IDE also registers the resource reference and message destination reference in your module's general deployment descriptor.

Note:

If your project's target server is the GlassFish/Sun Java System Application Server, the IDE automatically configures a destination and connection factory for the message-driven bean when you create the bean. If you are deploying to a different application server, you have to configure the server-specific deployment descriptors and the server resources yourself.

15.3.5 How to Use a Service Locator

A service locator is a class that provides a single, reusable way to obtain a reference to the following:

  • An enterprise bean's local and/or remote home interfaces

  • A JMS connection factory and topic destination

  • An e-mail session

  • A JDBC data source

  • The URL, name, or boolean value for an environment entry

You can create a regular service locator or one that caches the obtained reference for further use. Generally you use a caching service regulator in web applications and a regular service locator in the business tier. Enterprise beans especially need non-caching service locators. Because each enterprise bean has a unique JNDI name space, a resource reference with the same name can be declared in multiple enterprise beans, potentially with different types.

To create a service locator:

  1. Choose File > New.

  2. From the Enterprise category, select Service Locator or Caching Service Locator.

To use a service locator:

Run any of the following commands:

In the Service Locator Strategy section, select Use Existing Class and specify the class name of the service locator. Use the Browse button to search for the class.

Note:

The service locator template is fully functional. You do not need to modify the code, although you can customize its caching behavior.

You can only create a service locator in a web application project or EJB module project.

For more information, see Section 15.3.6, "How to Access a Connection Pool from a Java Class."

15.3.6 How to Access a Connection Pool from a Java Class

Applications that are deployed to servers often need to access databases that reside on remote machines. You therefore have to set up a JDBC connection pool on the server that points to the database. You then create a data source that connects to the connection pool and use the data source's JNDI name to acquire a connection to the database. See Section 22.3.7, "How to Set up a Connection Pool."

To access a database from an enterprise application:

  1. (Optional) Create a service locator class to handle getting the reference to the database.

  2. Open the Java file from which you want to access the database. In the Source Editor, right-click the file and choose Insert Code > Use Database. For more information see Section 23.1, "About Working and Connecting with Databases."

  3. Enter a JNDI name for the database connection. This name must be the same as the JNDI name of the JDBC data source for the database on the target server. See Section 23.3.2, "How to Connect to the Java DB Database."

    If you are deploying to the GlassFish Server, you can also generate a connection pool and data source for the database connection by selecting the Create Server Resources checkbox. The resources are created under the project's Server Resources node.

  4. Select the database to which you want to connect in the Connection drop-down list. If the database is not listed, do the following:

    1. If the JDBC driver for the database server is not registered in the IDE, click Add Driver.

    2. Click Add Connection to connect to the database.

  5. Under Service Locator Strategy, specify whether to generate inline lookup code or use an existing service locator. Click Browse to search for the service locator class name.

  6. Click OK.

The Use Database command is only available in EJB module and web application projects.

15.3.7 How to Send an Email from a Java File

  1. (Optional) Create a service locator class to handle getting the reference to the database.

  2. Open the Java file from which you want to send the e-mail message. The file must be in an EJB module project or a standard web application project. You cannot generate lookup code in a free-form web application project.

  3. In the Source Editor, right-click the file and choose Insert Code > Send E-mail.

  4. Specify the JNDI name of the mail resource on the application server.

  5. Under Service Locator Strategy, specify whether to generate inline lookup code or use an existing service locator. Click Browse to search for the service locator class name.

  6. Click OK.

    The IDE creates two methods:

    • getSession. This method looks up the mail resource and creates a mail session.

    • sendMail. This method constructs and sends the e-mail.

    The IDE also registers the resource reference in your module's general deployment descriptor.

  7. In your code, call the sendMail method and pass the e-mail address, subject, and body as parameters.

Note:

You have to configure the JavaMail resource on the application server yourself. If your project's target server is the GlassFish server, you can use the JavaMail Resource template found in the New File wizard GlassFish.

If your project's target server is the GlassFish server, the IDE automatically configures the resource reference in the application-specific deployment descriptor. If you are deploying to a different application server, you have to configure the server-specific deployment descriptors yourself.

For additional information see Section 11.9.1, "How to Edit Deployment Descriptors," and Section 15.5.3, "How to Edit the Deployment Descriptors of an EJB Module."

15.4 Calling an Enterprise Bean

Calling an enterprise bean is the process of getting a reference to the enterprise bean so that you can call its methods. The IDE can assist you in calling an enterprise bean from any Java class in an EJB module, web application, or enterprise application client.

15.4.1 How to call an Enterprise Bean

  1. Open the IDE project that contains the enterprise bean that you want to call.

  2. Open the file from which you want to call the enterprise bean.

  3. In the Source Editor, right-click anywhere in the body of the class and choose Insert Code > Call Enterprise Bean.

  4. In the dialog box, select the enterprise bean that you want to call.

  5. (Optional) Type a new name for the reference.

  6. Specify whether to reference the local interface or the remote interface. To reference a bean's local interface, the class that is referencing the bean must be packaged in the same enterprise application as the enterprise bean.

  7. Click OK.

When you call an enterprise bean, the following occurs:

Java EE projects:

  • The IDE uses the @EJB annotation to indicate a dependency on another bean. In the Java class from which you are calling the enterprise bean, the IDE adds code similar to the following:

    @EJB

    private NewSessionRemote newSessionBean;

  • The enterprise bean project is added to the caller project's classpath.

J2EE 1.4 projects:

  • A lookup method is created in the caller class.

  • The enterprise bean project is added to the caller project's classpath.

  • A reference to the entity or session bean being called is added to the deployment descriptor of the caller project. If and where the reference is added depends on which of the following applies:

    • If the lookup is made from an enterprise bean implementation class, the reference is added to the corresponding bean.

    • If the lookup is made from any class of a web application, the reference is added to the web application.

    • If the lookup is made from a plain Java class of an EJB module, no reference is added. In this case, the reference has to be added manually to the bean calling the plain Java class.

Note:

The IDE cannot assist you when calling an enterprise bean from a free-form web application project.

15.5 Building and Deploying an EJB Module

There are two ways to build an EJB module:

When an EJB module is part of an enterprise application, its enterprise beans can be accessed from external clients and web application modules through its remote interfaces, and by other modules in the enterprise application through its local interfaces. All of the JAR files needed for execution are packaged in the enterprise application's EAR file and the classpath to these JAR files are written in the EJB module's manifest file. This is the most common way of deploying an EJB module.

There are two deployment commands:

15.5.1 How to Build an EJB Module as Part of an Enterprise Application

The IDE packages all of the necessary JAR files as part of the Java EE application and not as part of the individual modules. This is the most common way of building an EJB module.

  1. In the Projects window, expand the enterprise application's Java EE Modules node and make sure that the EJB module is listed. If you have not added the EJB module to the enterprise application, right-click the Java EE Modules node, choose Add Java EE Module, and select the EJB module.

  2. Right-click the enterprise application project and choose Build. Or, if the enterprise application project is the main project, choose Run > Build Main Project (F11) from the main menu.

    Note:

    To set a project as the main project right-click the project in the Projects window and choose Set as Main Project, or, choose Run > Set Main Project from the menu bar and select the project in the sub-menu.

When you build an EJB module as part of an enterprise application, the IDE does the following:

  • Compiles the classes to the project's build/jar-module folder.

  • Places any JAR files, libraries, or directories that are on your project's classpath and are scheduled for inclusion in deployment in the enterprise project's build folder.

  • Builds the EJB module's JAR file to the EJB module project's dist folder and copies it to the enterprise application project's build folder. The EJB module JAR file does not contain any of the classpath elements.

  • Puts a Class-path entry in the EJB module's manifest file for all included JAR files and puts a . entry if there is at least one directory on the project's classpath scheduled for inclusion in deployment. This mechanism ensures that the JAR files and directories can be used from the EJB module even if they reside in the EAR project and not in the EJB module itself.

  • Builds the enterprise application EAR file to the enterprise application project's dist folder.

15.5.2 How to Build a Stand-alone EJB Module

The IDE packages the necessary JAR files with the EJB module JAR file.

To build a stand-alone EJB module:

Right-click the EJB module project in the Projects window and choose Build. Or, select the EJB module project in the Projects window and choose Run > Build Project (Build Main Project (F11) if the EJB module project is set as the main project).

When you build a EJB module project as a stand-alone module, the IDE does the following:

  • Compiles the classes to the project's build/jar folder.

  • Places any JAR files, libraries, or directories that are on your project's classpath and are scheduled for inclusion in deployment into the build/jar folder.

  • Builds the EJB module's JAR file to the EJB module's dist folder. The JAR file includes all classpath items scheduled for inclusion in deployment.

Note:

To mark a classpath item for inclusion in deployment in the EJB module's Project Properties dialog box, right-click the module's Libraries node and choose Properties, then select the checkbox for each classpath item you want to include in deployment.

15.5.3 How to Edit the Deployment Descriptors of an EJB Module

If you are developing enterprise beans on the Java EE 5 platform and deploying to a Java EE 5 compliant application server, you develop enterprise beans using EJB 3.0 technology.

If you are developing enterprise beans on the Java EE 6 or Java EE 7 platform and deploying to a Java EE-compliant application server, you develop enterprise beans using EJB 3.1 technology. EJB 3.0 and EJB 3.1 technology support the use of annotations in your code to describe behavior that was described using deployment descriptors in EJB 2.1 technology. As a result, deployment descriptors files are no longer required when deploying to a Java EE-compliant server. EJB 3.0 and EJB 3.1 technology also support the use of deployment descriptors. You may need to use a combination of annotations and deployment descriptors in your project when you configure your project, for example to configure security settings.

For EJB modules, there are two types of deployment descriptors:

  • The general Java EE deployment descriptor that configures deployment settings on any Java EE-compliant implementation. The general EJB deployment descriptor is called ejb-jar.xml. The IDE provides a visual editor for the general deployment descriptor and automatically updates the descriptor file when you edit your code.

  • The server-specific deployment descriptor that configures deployment settings for the application server to which you are deploying. For the Sun Java System Application Server, the IDE automatically updates the deployment descriptor files as you edit your files. For all other application servers, you have to write the server-specific deployment descriptors yourself.

The IDE provides a visual deployment descriptor editor to help you edit some descriptor files. You can also use the XML editor to edit your descriptor files.

To edit ejb-jar.xml:

  1. In the Projects window, expand the Configuration Files node for your EJB module project.

  2. Double-click ejb-jar.xml to open the file in the visual editor.

  3. Select one of the following tabs:

    • General. This tab enables you to specify general information about the EJB module, details about security roles and descriptor details about each of the enterprise beans in the module.

    • CMP Relationships. This tab enables you to view and modify CMP relationships for CMP beans in your module.

    • XML. This tab enables you to edit the descriptor file in the XML editor.

  4. Edit the properties.

  5. Save your changes.

To edit glassfish-ejb-jar.xml:

  1. In the Projects window, expand the Configuration Files node for your EJB module project.

  2. Double-click glassfish-ejb-jar.xml to open the file in the visual editor.

  3. Select a tab at the top of the editor.

  4. Edit the descriptor file as necessary and save your changes.

To edit the server-specific deployment descriptor for any other application server:

  1. Double-click the deployment descriptor node in the Projects window.

  2. The IDE opens the XML source of the deployment descriptor in the Source Editor.

  3. If you enter any XML syntax errors the IDE automatically alerts you. To fully ensure your changes have not cause any errors, you should verify the EJB module.

  4. In the Projects window, right-click the enterprise application project and choose Run or Deploy.

For additional information see Section 22.4.1, "How to Register a Server Instance."

To deploy an enterprise application:

If the module is part of an enterprise application, right-click the enterprise application project and choose Debug.

If the module is a stand-alone EJB module, right-click the EJB module project and choose Debug.

15.5.4 How to Verify the Deployment Descriptors of an EJB Module

Before you deploy an enterprise application or any stand-alone web or EJB module to the application server, you should verify it, to ensure it is properly implemented to the Java EE specification. When the target server for the project is the Sun Java System Application Server or GlassFish application server, use the verifier tool to validate both Java EE and application server-specific deployment descriptors against their corresponding DTD files and display errors and warnings if a module or application is not compliant. You can verify deployment descriptors in EAR, WAR, RAR, and JAR files.

The verifier tool is not simply an XML syntax verifier. Rules and interdependencies between various elements in the deployment descriptors are verified. Where needed, classes in your module are examined to ensure that what is referred to in the deployment descriptors actually exists and works when deployed.

To verify a project deployment descriptors:

  1. Right-click any web application module, EJB module, or enterprise application project in the Projects window and choose Verify.

  2. The Verifier window opens and displays all the results.

  3. Filter the results according to your needs:

    • Click Failures Only to display only failures.

    • Click Failures and Warnings Only to display only failures and warnings.

  4. Make appropriate changes, if any, and verify the project again.

Note:

Not all failures to comply with the Java EE specification cause the application to fail. However, modules that fail to comply with the specification might not be portable between application servers. The verifier tool helps you ensure your code is not locked into running only on a specific application server.

15.5.5 How to Deploy a Stand-alone EJB Module

Enterprise beans in a stand-alone EJB modules can only be accessed through their remote interfaces. All of the JAR files needed for execution are packaged in the EJB JAR file itself.

To deploy a stand-alone EJB module:

In the Projects window, right-click the EJB module project and choose Run or Deploy.

15.5.6 How to Debug an EJB Module

There are two ways to debug an EJB module:

  • As a stand-alone EJB module

  • As part of an enterprise application

To debug a stand-alone EJB module:

  • In the Projects window, right-click the EJB module project and choose Debug.

When you debug a stand-alone EJB module, the IDE does the following:

  • Compiles the EJB module if necessary.

  • Stops the application server and starts it in debug mode.

  • Deploys the EJB module to the application server.

  • Starts a debugging session, attaches the debugger to the server, and opens the debugger windows at the bottom of the IDE screen. Since an EJB module does not have an executable class, there are no local variables or calls on the call stack. To debug the functionality in the EJB module, use an application client or web application to access the EJB module's methods.

To debug an enterprise application:

In the Projects window, right-click the enterprise application project and choose Debug.

When you debug an enterprise application, the IDE does the following:

  • Compiles the EAR file if necessary.

  • Stops the application server and starts it in debug mode.

  • Deploys the enterprise application to the application server.

  • Starts a debugging session, attaches the debugger to the server, and opens the debugger windows at the bottom of the IDE screen. If the application has a designated web application and URL to run, the IDE opens the URL in the external browser.

Note:

If your EJB module is part of an enterprise application, you should always debug it by running the debug command on the enterprise application project. Since the IDE does not know which enterprise applications an EJB module project belongs to, running the Debug command on an EJB module project deploys it as a stand-alone module.

When debugging an enterprise application, if your application contains any projects not listed in the Packaging page of the enterprise application, you must explicitly specify these projects if you want the IDE to include them in the classpath when you debug the application. To specify the projects to include, right-click the enterprise application project node in the Projects window and choose Properties. In the Properties dialog box, select the Libraries category and add the projects to the Embedded Classpath Elements list.

The debugger windows filter out any information from method calls running on the server.

For additional information see Section 22.3.1, "How to Register a Server Instance."

15.5.7 How to Profile an EJB Module

There are two ways to profile an EJB module:

  • As a stand-alone EJB module

  • As part of an enterprise application

If your EJB module is part of an enterprise application, you should running the profile command on the enterprise application project. Since the IDE does not know which enterprise applications an EJB module project belongs to, running the Profile command on an EJB module project deploys it as a stand-alone module.

If you are deploying your EJB module or enterprise application to a local installation of the GlassFish server, go to the main menu and choose Profile > Profile Project and choose the project in the sub-menu, or, by right-click the project node in the Projects window and choosing Profile from the pop-up menu.

If you are deploying your EJB module or enterprise application to a remote server, you must attach the IDE to the remote server and profile the application in Attach mode. The Attach Wizard can help you configure the remote server to accept attachment.

To profile a stand-alone EJB module:

  1. In the Projects window, right-click the EJB module project and choose Profile.

  2. Select a profiling task and click Run.

When you profile a stand-alone EJB module, the IDE does the following:

  • Compiles the EJB module if necessary.

  • Stops the application server and starts it in profile mode.

  • Deploys the EJB module to the application server.

  • Starts a profiling session, attaches the profiler to the server, and opens the Profiler window in the IDE. After the application is deployed to the server, you should invoke its code the same way as you would for debugging or just evaluating application functionality. You can use an application client or a web application to access the EJB and invoke its code. You can view the profiling data once the application code is invoked.

To profile an enterprise application:

  • In the Projects window, right-click the enterprise application project and choose Profile.

  • Select a profiling task and click Run.

Note:

If you are analyzing application performance, choose the Profile Projects & Subprojects Classes filter to ensure that the classes in your EJB module and web module projects are profiled. If you do not choose this filter, the classes in the EJB module and web module are not profiled.

Follow this procedure to limit profiling the classes in the enterprise application:

  1. In the Analyze Performance pane, choose the Profile Projects & Subprojects Classes filter and then click Show Filter Value.

  2. Click To Quickfilter in the dialog box.

  3. In the Set Quick Filter dialog, select a filter type, edit the filter values to limit the classes that are profiled, and click OK.

  4. Make sure that Quick Filter is selected in the Filter drop-down list when you run the profiling session.

When you profile an enterprise application, the IDE does the following:

  • Compiles the EAR file if necessary.

  • Stops the application server and starts it in profile mode.

  • Deploys the enterprise application to the application server.

  • Starts a profiling session, attaches the profiler to the server, and opens the Profiler window in the IDE. If the application has a designated web application and URL to run, the IDE opens the URL in the external browser.

For more on profiling see Chapter 8, "Testing and Profiling Java Application Projects."

15.5.8 How to Test an EJB Module

To use local JUnit tests to test an EJB module that is deployed on a server, you must configure the tests to act as a remote client of the EJB module. This means you can only access the EJB module through its remote interfaces. For information on JUnit unit testing, see Section 8.3, "Creating a Unit Test."

Usually, you have some entity beans and a session bean with remote interfaces that provides clients access to the entity beans. You have to generate tests for the session bean's bean class and modify the test file to reference the session bean and test each of its business methods.

To generate tests for an EJB module:

  1. Create a service locator file somewhere in the test package source root.

  2. Open the enterprise bean's bean class in the Source Editor and choose Tools > JUnit Tests > Create Tests (Ctrl+Alt+J). Accept the default options in the dialog box and click OK.

  3. In the test class, delete the test methods that just test EJB infrastructure methods such as testEjbCreate and testEjbRemove.

  4. Declare a variable for the remote home interface.

  5. In the setUp method, write code to instantiate this variable, as in the following example:

    Example 15-1 Instantiate a Variable for the Remote Home Interface

    protected void setUp() throws NamingException, 
                           CreateException, RemoteException {
        ServiceLocator sl = new ServiceLocator();
        newSessionHome = (NewSessionRemoteHome)sl.getRemoteHome("ejb/NewSessionBean", 
                          NewSessionRemoteHome.class);
    }
    
  6. In each test method, retrieve a remote interface and test the business method, as in the following example:

    Example 15-2 Retrieve and Test a Remote Interface

    try {
        NewSessionRemote newSession = newSessionHome.create();
        assertEquals("name", newSession.getName(new Integer(1)));
    }
    catch (Exception e) {
        fail(e.toString());
    }
    

Note:

You do not have to use a service locator class. You can write the lookup code from scratch.

15.6 Developing EJB 2.1 Entity Beans

An entity bean is an enterprise bean that represents data that is typically stored in a database. Entity beans are part of the EJB 2.1 specification and are used in J2EE 1.4 enterprise applications. In Java EE enterprise applications, you use the Java Persistence API to interact with databases. See Section 16.1, "About Developing with Java Persistence."

In J2EE 1.4 applications, entity beans are used to represent a business entity object that exists in persistent storage. In Java EE applications, entities are used instead of entity beans. For more about persistent entity objects, see Section 16.3.1, "How to Create an Entity Class."

15.6.1 About Container-Managed Relationships

Like a table in a relational database, an entity bean may be related to other entity beans. With bean-managed persistence, the code that you write implements the relationships. But with container-managed persistence, the EJB container manages the relationships for you.

For instance, consider the cmpcustomer example downloadable from:

http://www.oracle.com/technetwork/java/javaee/documentation/j2ee-jsp-136778.html

The example defines relationships between customers, addresses, and subscriptions. Each customer may have one or more addresses. A customer may also have zero or more subscriptions. Similarly, a single subscription may be associated with many customers. In order for this example to work correctly, the relationships between the entity beans representing these database tables must be configured correctly.

15.6.2 Container-Managed Relationships in the IDE

When you generate CMP entity beans from a database, the IDE automatically registers all of the container-managed relationships based on the relationships in the database. The CMP relationships are described in the module's ejb-jar.xml descriptor file. The IDE also automatically generates the necessary CMP fields in your source code.

When defining a CMP relationship, you may need to set the following properties.

  • Direction. Relationships between databases can either be unidirectional or multidirections. For example, in the above cmpcustomer example, the relationship between customers and the addresses is unidrectional, because the customer table references the address table but the address table does not reference the customer table. The relationship between subscriptions and customers, on the other hand, is multidirectional.

  • Multiplicity. Multiplicity (also known as cardinality) describes how many instances of each side of the relationship there can be. Entity beans can have the following multiplicity:

    • One-to-one. Each entity bean instance is related to a single instance of another entity bean.

    • One-to-many. An entity bean instance can be related to multiple instances of the other entity bean. In the above cmpcustomer application, for example, customers have a one-to-many relationship to addresses.

    • Many-to-one. Multiple instances of an entity bean can be related to a single instance of the other entity bean.

    • Many-to-many. The entity bean instances can be related to multiple instances of each other. For example, in the above cmpcustomer application, subscriptions and customers have a many-to-many relationship.

  • Cascade Delete. Often, the existence of one table is often dependent on the existence of the table that references it. For example, in the above cmpcustomer example, you may add and delete individual addresses for a customer. Because an address instance must be associated to a customer, however, when you delete a customer, you are also automatically deleting all addresses associated to that customer.

    The application server takes care of this automatically through the cascade delete setting. When you enable cascade delete in a relationship, all related bean instances are deleted when the bean referring to them is deleted.

15.6.3 How to Generate CMP Entity Beans from a Database

In addition to writing CMP entity beans from scratch, you can also generate a set of CMP entity beans from an existing database connection or from a database schema.

  1. Make sure that you have access to the database source from which you want to generate the entity beans:

    • If you want to generate entity beans from an existing database connection, make sure the database is running and you have registered a connection to it in the Services window.

    • If you want to use a database schema, make sure the database schema file exists in your project's conf folder.

  2. Right-click the EJB module project node in the Projects window and choose New > CMP Entity Beans from Database.

  3. Select the database source:

    • JDBC Connection. The drop-down list displays all your registered database connections. To add a database connection, choose Add Connection from the drop-down list.

    • Database Schema. The drop-down list displays all of the database schema files in your project's conf folder. If your project does not contain any database schema files, this option is disabled. For more information see Section 23.2.8, "How to Obtain a Database Schema."

  4. In the Location drop-down list, select the source root to which you want to add the enterprise beans.

  5. In the Package drop-down list, select an existing package or type a new package name.

  6. Specify whether to generate finder methods for all CMP fields.

  7. Specify whether to add the CMP Fields and CMR fields to the local interfaces.

  8. Click Next.

  9. Select any table from the list on the left and click Add. Then click Finish.

When you generate entity beans from a database, the IDE does the following:

  • If creating the entity beans from a database connection, grabs the database structure and stores it in a database schema file in your project's conf folder.

  • Creates an entity bean for each of the selected tables and any tables the selected tables reference. A node for each entity bean is displayed in the project's Enterprise Beans node. By default, the generated entity beans only have local interfaces. Each entity bean contains a CMP field for each column in the table and a CMR field for any column that references another table.

  • Configures any container-managed relationships in the EJB module's ejb-jar.xml deployment descriptor.

If your project's target server is the Sun Java System Application Server/GlassFish, the IDE also does the following:

  • Creates a sun-cmp-mappings.xml file under the Configuration Files node that contains CMP mapping information for the entity beans. The IDE maps all CMP fields to the correct columns in the database. To view and edit CMP mappings, double-click sun-ejb-jar.xml or sun-cmp-mappings.xml, and then click the XML tab to edit the file in the XML editor.

  • Prepares a connection object and JDBC resources for the project which are configured on the server when you run or deploy the project. You can view and edit these resources in the sun-resources.xml file in the Projects window Server Resources node.

Note:

If you are deploying to the JBoss or Oracle WebLogic Servers, you have to write your server-specific deployment descriptors and configure the required server resources yourself.

15.6.4 How to Define a Finder Method for an Entity Bean

A finder method is a type of query method that is used in an EJB 2.1 entity bean. (Select methods are the other type of query method.) Finder methods are unique to entity beans because entity beans represent data in a database that can be identified and found. Session beans do not represent database data, therefore, they do not have data that can be found.

To define a finder method for an entity bean:

  1. Open the bean class in the Source Editor.

  2. Right-click anywhere in the Source Editor and choose Insert Code > Add Finder Method.

  3. In the Add Finder Method dialog box, define the method signature:

    1. Add text to the base findBy name of the method.

    2. Specify any parameters that the method needs.

    3. Specify which interfaces to add the method to (remote and/or local).

    4. Specify the return cardinality for the method. This setting should match the return cardinality of the statement in the database. If you select One, the statement returns the bean's interface. If you select Many, the statement returns a java.util.Collection object.

    5. If the bean uses container-managed persistence (CMP), enter the EJB QL statement that the method uses to find the enterprise bean or beans that the method is to return. For related information see Section 15.6, "Developing EJB 2.1 Entity Beans."

  4. Click OK to create the method.

    The IDE adds the method signature to the bean's interfaces and registers the method in the general deployment descriptor.

    • If the entity bean uses CMP, you are done. The container implements the finder method from the signature in the home interface or local home interface, so the home interface and the local home interface are the only places the method appears.

    • If the entity bean uses bean-managed persistence (BMP), the IDE adds an empty ejbFindyourname method to the bean class so you can implement the method. You must implement the ejbFindyourname method yourself.

15.6.5 How to View, Edit or Delete Existing Finder Methods

  1. In the Projects window, expand the Configuration Files node for your EJB module project.

  2. Double-click ejb-jar.xml. The graphical editor opens in the General view.

  3. Click the XML tab and make your changes in the XML editor.

If you make changes to ejb-jar.xml you must also make corresponding changes in your bean source code.

Note:

When the IDE adds a finder method to an entity bean, it does not save the bean class or the bean interfaces. Only when you compile or save the project are the changes saved to disk.

  • To fully remove a finder method from an enterprise bean, do the following:

    • Delete the method from the bean's source code.

    • Delete the finder query from ejb-jar.xml.

15.6.6 How to Add EJB QL to a Finder or Select Method

EJB QL is the generic query language used by EJB 2.1 finder methods and select methods, the two types of entity bean query methods. You must use EJB QL to define queries that these methods use to return data. When you deploy the bean containing a finder or select method, the application container translates your generic EJB QL to the persistence mapping the container makes (for example, the version of SQL required to access the SQL databases associated with the container).

Finder methods are unique to entity beans because entity beans represent data in a database that can be identified and found. A finder method can find and return an entity bean or a collection or set of entity beans.

Select methods are unique to entity beans that use container-managed persistence (CMP beans). A select method is more flexible than a finder method and is visible only to the bean class, and therefore can be used only by methods of the bean class. In addition to returning a bean or a collection of beans, a select method can also return the value of a field.

To add or edit the EJB QL in a finder method or select method, do one of the following:

  • When you define a new finder method or a new select method, the Add Finder Method dialog box has EJB QL fields that you can fill in.

  • If the finder or select method already exists, you can edit its EJB QL as follows:

    • In the Projects window, expand the Configuration Files node for your EJB module project.

    • Double-click ejb-jar.xml. The graphical editor opens in the General view.

    • Click the XML tab and make your changes in the XML editor.

Note:

If you make changes to CMP fields in ejb-jar.xml you must also make corresponding changes in your bean source code.

15.6.7 How to Define a Select Method for a CMP Entity Bean

Select methods are a type of query method that, like finder methods, is used in EJB 2.1 CMP entity beans to query databases. A select method is more flexible than a finder method and is visible only to the bean class; therefore, a select method can be used only by methods of the bean class. A select method inherits the transaction context of the method that calls it. In addition to returning a bean or a collection of beans, a select method can also return the value of a field. Select methods are only available for entity beans that use container-managed persistence (CMP).

To define a select method for a CMP entity bean:

  1. Open the bean class in the Source Editor.

  2. Right-click anywhere in the Source Editor and choose Insert Code > Add Select Method.

  3. In the Add Select Method dialog box, define the method signature:

    1. Add text to the base ejbSelectBy name of the method.

    2. Choose the method's return type from the combo box:

      CMP field value: If the method returns the value of a CMP field, choose the appropriate Java or primitive data type, such as java.lang.String or int.

      enterprise bean: If the method returns an enterprise bean, type the bean's type in the combo box.

      multiple beans: If the method returns more than one bean, type java.util.Set or java.util.Collection in the combo box. Use java.util.Set if the returned beans cannot be duplicates. Use java.util.Collection if the returned beans can be duplicates.

    3. Enter the EJB QL statement that the method uses to find the data to be returned.

    4. Specify any parameters that the method needs.

  4. Click OK to create the method.

The IDE adds the method signature to the bean class and registers the select method to the EJB module's deployment descriptor.

15.6.8 How to View, Edit or Delete Existing Select Methods

To manage existing select methods:

  1. In the Projects window, expand the Configuration Files node for your EJB module project.

  2. Double-click ejb-jar.xml. The graphical editor opens in the Details view.

  3. Click the XML tab and make your changes in the XML editor.

    If you make changes to ejb-jar.xml you must also make corresponding changes in your bean source code.

15.6.9 How to Define a CMP Field for an Existing Entity Bean

An EJB 2.1 entity bean is the tool that a J2EE 1.4 enterprise application uses to represent data in a database. If it uses container-managed persistence (CMP), the bean must have a set of CMP fields that the container uses to map to fields in the database.

To define a CMP field for an existing entity bean:

  1. Open the bean class in the Source Editor.

  2. Right-click anywhere inside the body of the class and choose Insert Code > Add CMP Field. This command is only enabled when you click within the body of the class (after the class declaration).

  3. Enter the name and type of the CMP field and click OK.

When you add a new CMP field to an entity bean, the IDE does the following:

  • Adds the get and set methods for the field to the bean class.

  • Registers the CMP field in the deployment descriptor.

15.6.10 How to View or Edit an Existing CMP Field

  1. In the Projects window, expand the Configuration Files node for your EJB module project.

  2. Double-click ejb-jar.xml. The graphical editor opens in the General view.

  3. Click the XML tab and make your changes in the XML editor.

    If you make changes to CMP fields in ejb-jar.xml you must also make corresponding changes in your bean source code.

Note:

If you use the Entity Beans from Database wizard to create the bean, the IDE can automatically create the CMP fields for all the fields in a database.

When you create a new CMP field you might need to configure the server-specific deployment descriptor. For example, the field might need to be mapped to a database column. If you are deploying to the Sun Java System Application Server, you must also make these changes in sun-ejb-jar.xml or sun-cmp-mapping.xml.

For more on configuring deployment descriptors, see "How to View or Edit an Existing CMP Field".

15.6.11 How to Configure CMP Mappings

If you are deploying to the GlassFish Server, the CMP mappings for your EJB module are specified in the sun-cmp-mappings.xml descriptor file in the module's src/conf directory. You use the XML editor to configure CMP mappings in sun-cmp-mappings.xml.

You might need to change the CMP mappings of your entity beans in the following situations:

  • The generated defaults are not adequate

  • You have modified your bean

  • You have modified your schema

To edit CMP mappings in sun-cmp-mappings.xml:

  1. In the Projects window, expand the Configuration Files node for your EJB module and double-click sun-cmp-mappings.xml.

  2. Edit the file and validate the XML.

  3. Save your changes.

Mapping Entity Beans to Tables

When you map the beans in sun-cmp-mappings.xml, you specify the schema and the primary table for each bean. Each bean must be mapped to at least one table within a single database schema. You can also map a bean to a secondary table. All beans related by container-managed relationships must be mapped to tables in the same schema.

If you do not have a database schema, you can capture the schema. In the New File wizard, select Persistence > Database Schema and save the schema in the src/conf directory of your project.

  • Primary Tables. A primary table is the table that most closely matches the bean you are mapping. A primary table must be selected for each CMP bean.

  • Secondary Tables. A secondary table enables you to map fields in your bean directly to columns that are not part of your primary table. You might want to do this if, for example, the data that represents a logical object is split across two or more tables.

    A secondary table must be related to the primary table by one or more columns whose associated rows have the same values in both tables. This link is called a reference key. Normally, this key is a foreign key in the primary table.

Note:

A secondary table differs from relationships. You use secondary tables when you want columns from another table to be fields in the same bean. You use relationship fields when there is a logical relationship between tables. For example, if you want the entire row of another table to be an object in a single bean, you would map that with a relationship.

For more about CMP relationships, see the following topic:

Mapping Fields to Columns

When you map CMP beans to a database, the CMP fields in each entity bean map to columns in either the primary or a secondary table. CMP fields can also be mapped to multiple database columns.

If you map a field to more than one column, all columns are updated with the value of the first column listed. Therefore, if the value of one of the columns is changed outside of an EJB application, the value is only read if the change was made to that first column. Writing a value to the database overwrites any conflicting changes made to any other columns.

Mapping Relationship Fields

When you have foreign-key relationships between database tables, you usually want to preserve those relationships in the CMP beans mapped to those tables. Container-managed relationships (CMR) determine how relationships between mapped CMP beans are stored in the database. CMRs enable navigation from one bean to another, in the same way that a foreign key enables navigation from one table to another.

15.6.12 How to Generate Database Tables at Runtime

When developing CMP entity beans, if your only requirement is that the beans are persisted to a database and you are not particular about the structure of the database, you can configure the application so that the application server generates the database and mappings. In this case, create your CMP entity beans, the bean fields, and the relationships in the IDE, then configure the application to generate the database tables and mappings when you deploy the application.

Note:

Unless you create entity beans from a database connection, the IDE assumes you want to generate the sun-cmp-mappings.xml file automatically. If you create CMP entity beans using the New Entity Bean template and manually set up your mappings by hand in a sun-cmp-mappings.xml file, the IDE ignores your settings and configures the mappings during deployment. To use your own sun-cmp-mappings.xml file, generate a CMP entity bean from any database. You can then delete the bean. The IDE automatically switches your project to pick up the existing sun-cmp-mappings.xml file.

To generate database tables at runtime:

  1. Make sure that your entity beans are set to use container-managed persistence and have their CMP fields and container-managed relationships correctly configured.

  2. In the Projects window, expand Configuration Files and double-click sun-ejb-jar.xml to open the file in the Visual Editor.

  3. Click the XML tab to open the XML editor.

  4. Specify the JNDI name for your database resource in the <jndi-name> property. Make sure that the name matches a database resource configured on your application server.

  5. Set the value of the <create-tables-at-deploy> element to True.

  6. To prevent an error when redeploying the application, set Drop Table At Undeployment to True. Alternatively, delete the tables manually in the Services window of the IDE.

  7. Make sure the database server in which you are generating the tables is running. If you are using the bundled Java DB server, expand the Databases node in the Servers window and right-click the Java DB node and choose Start Server.

  8. Deploy your application by right-clicking the project node and choosing Run.

When you click Run, a table is generated for each CMP bean. In each table, a column is created for each CMP field and the relationships between the tables are generated based upon the relationships between your CMP beans. To see the created tables go to the Services window Tables node for your database connection.

15.6.13 How to Edit CMR Field Mappings

When you have foreign-key relationships between database tables, you usually want to preserve those relationships in the CMP beans mapped to those tables. Container-managed relationships (CMR) determine how relationships between mapped CMP beans are stored in the database. CMRs enable navigation from one bean to another, in the same way that a foreign key enables navigation from one table to another.

When mapping relationship fields, you typically use a foreign key to connect your tables. If there is no foreign key, then you must create key column pairs to act as the key between tables. The columns in each pair are expected to have the same value.

If you generate CMP entity beans from a database schema, the IDE generates the necessary relationships in the deployment descriptor for you based on the database schema. If you are generating CMP entity beans from scratch and need to configure CMRs for your application, you must edit the deployment descriptor file in the XML editor.

If you are deploying to the GlassFish Server, you configure CMR fields in the sun-cmp-mappings.xml. If you are deploying to a different application server, you have to configure CMR fields yourself in the server-specific deployment descriptors.

To edit CMR field mappings:

  1. Make sure you have configured ejb-jar.xml to specify your data source and the CMP relationships, and that you have specified the primary and any secondary tables. See "Mapping Relationship Fields."

  2. In the Projects window, expand the Configuration Files node for your EJB module and double-click sun-cmp-mappings.xml.

  3. Edit the XML to create the necessary fields. Use the IDE's code completion feature to help you edit the deployment descriptor properties.

  4. Validate the XML file.

  5. Update your source code where necessary.

Note:

You should exercise caution when editing deployment descriptors in XML and always validate your XML file to avoid errors.