站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题Generating Primary Key Values in CMP Beans

Generating Primary Key Values in CMP Beans

摘要: The Sun Java System Application Server supports automatic primary key generation for EJB 1.1, 2.0, and 2.1 CMP beans. To specify automatic primary key generation, give the prim-key-class element in the ejb-jar-xml file the value java.lang.Object. CMP beans with automatically generated primary keys can participate in relationships with other CMP beans. The Sun Java System Application Server does not support database-generated primary key values.

If the database schema is created during deployment, the Sun Java System Application Server creates the schema with the primary key column, then generates unique values for the primary key column at runtime.

If the database schema is not created during deployment, the primary key column in the mapped table must be of type NUMERIC with a precision of 19 or more, and must not be mapped to any CMP field. The Sun Java System Application Server generates unique values for the primary key column at runtime.

Getting Started

Before you begin, you have to install Sun Java System Application Server Platform Edition 8.1 (download) on your computer. You cannot deploy enterprise applications to the bundled Tomcat server. You also have to register the application server in the IDE by choosing Tools > Server Manager.

This example also uses MySQL instead of PointBase as the database server. To learn how to set up MySQL in NetBeans and on the application server, see this document.

Creating the Database Table

Our example uses a very simple database table that lists customers by ID, last name, and first name.

  1. Register the MySQL driver in the IDE. In the Runtime window, expand Databases > Drivers, right-click the Drivers node, and choose Add Driver.
  2. Register the connection to any existing MySQL database. In the Runtime window, right-click the node for the MySQL driver and choose Connect Using. (For more information about registering MySQL in NetBeans IDE, see this document.)
  3. Create the sample table in the database. Right-click the node for the database connection and choose Execute Command. In the Command field, type the following command and click Execute:
    CREATE TABLE customer (
           id BIGINT(19) NOT NULL, -- this column will be automat. populated
           lastName varchar(25) NOT NULL,
           firstName varchar(30) default NULL,
           PRIMARY KEY  (id));

Creating the EJB Module

When you generate the CMP beans from the database connection, the IDE will automatically register the id column as the primary key and create a CMP field and finder method for it. This forces you to already know the primary key before you can run the ejbCreate method.

You need to edit the CMP bean to get the primary key from the application server instead and make the appropriate changes to the deployment descriptor and ejbCreate method.

Coding the CMP Bean

  1. Choose File > New Project (Ctrl-Shift-N) from the main menu and create a new EJB Module project named CustomerModule.
  2. Right-click the CustomerModule project and choose New > CMP Beans from Database. Select the MySQL database connection and specify org.bank as the package. In the next page of the wizard, select the customer table from the database and click Finish.
    The IDE creates the CMP bean for the customer table.
  3. Delete the id CMP field. In the Projects window, expand Enterprise Beans > CustomerEB > CMP Fields, right-click the id node, and choose Delete.
  4. Change the ejbCreate and ejbPostCreate methods in CustomerBean to the following:
    public java.lang.Object ejbCreate(java.lang.String lastName, java.lang.String firstName)
        throws javax.ejb.CreateException {
      if (lastName == null) {
        throw new javax.ejb.CreateException("The field \"lastName\" must not be null");
      }
    
      // TODO add additional validation code, throw CreateException if data is not valid
      setLastName(lastName);
      setFirstName(firstName);
    
      return null;
      }
    
    public void ejbPostCreate(java.lang.String lastName, java.lang.String firstName) {
      // TODO populate relationships here if appropriate
    }
    We've done the following:
    • Removed id from the parameters of both methods.
    • Changed the return type of ejbCreate to java.lang.Object.
    • Removed the if clause in ejbCreate that checked that id is not null.
    • Removed the code that set the id field for this bean.
  5. Go to the CustomerLocalHome interface and remove id from the parameters of the create method:
    ...
    public org.bank.CustomerLocal create(java.lang.String lastName, java.lang.String firstName)
        throws javax.ejb.CreateException;
    ...
  6. In CustomerLocalHome, change the parameter type for the findByPrimaryKey method from java.lang.Long to java.lang.Object:
    ...
    org.bank.CustomerLocal findByPrimaryKey(java.lang.Object key)
        throws javax.ejb.FinderException;
    ...
  7. Double-click ejb-jar.xml to open it in the Source Editor. In the General section, change the Primary key class to java.lang.Object.
  8. Click XML at the top of the ejb-jar.xml editor to view the XML source code for the deployment descriptor. Go to the primkey-field element and delete it.
  9. Choose File > Save All.

Creating the Session Bean

Now we need to create a facade session bean that will access the CMP bean.

  1. Right-click the CustomerModule project and choose New > Session Bean. Name the bean CustomerFacade, put it in the org.bank package, and set it to be Stateless and have only remote interfaces.
  2. In the CustomerFacadeBean class, right-click and choose Enterprise Resources > Call Enterprise Bean. Select CustomerEB and click OK. The IDE inserts the lookupCustomerBean method.
  3. Declare a private CustomerLocalHome customerHome object and change the ejbCreate method to call the lookupCustomerBean method:
    ...
    private javax.ejb.SessionContext context;
    private CustomerLocalHome customerHome;
    ...
    
    public void ejbCreate() {
      customerHome = lookupCustomerBean();
    }
    ...
  4. Add the following business methods to CustomerFacadeBean:
    public void createCustomer(String lastName, String firstName) throws Exception {
      customerHome.create(lastName, firstName);
    }
    
    public Collection getLastName(String firstName) throws Exception {
     ArrayList names = new ArrayList();
     Iterator it = customerHome.findByLastName(firstName).iterator();
       while(it.hasNext()){
          names.add(((CustomerLocal)it.next()).getLastName());
       }
      return names;
    } 
  5. In the Source Editor, right-click the name of each of the two methods you just added and choose EJB Methods > Add to Remote Interface.
  6. Choose File > Save All.

Setting the Datasource Class Name

When you create CMP beans from a database, the IDE automatically creates a connection pool and data source for the database connection. A known bug in NetBeans 4.1 is that the IDE generates connection pools for MySQL databases with the wrong datasource class name. You have to change the class name yourself.

  1. Expand Server Resources and double-click the connection-pool-mysql.sun-resource node.
  2. Change the value of the DataSource Classname property to com.mysql.jdbc.jdbc2.optional.MysqlDataSource.
  3. Close the property sheet.

Testing the EJB Module

Our EJB Module is now set up and ready to go. Let's put it through its paces by populating the database and writing a quick JUnit test case to test the two business methods.

Coding the JUnit Tests

  1. Select CustomerFacadeBean in the Projects window or Source Editor and choose Tools > JUnit Tests > Create Tests (Ctrl-Alt-J). Accept the default options in the dialog box and click OK. The IDE creates CustomerFacadeBeanTest and opens it in the Source Editor.
  2. Declare a private CustomerFacadeRemote customerFacade object:
    ...
    public class CustomerFacadeBeanTest extends TestCase {
      private CustomerFacadeRemote customerFacade;
    ...
    Note: If you the Source Editor complains that it cannot find CustomerFacadeRemote, just build the project by right-clicking the project node in the Projects window and choosing Build Project. The error disappears.
  3. Change the setUp method as follows:
    ...
    protected void setUp() throws Exception {
      InitialContext ctx = new InitialContext();
      Object obj = ctx.lookup("ejb/CustomerFacadeBean");
      customerFacade = ((CustomerFacadeRemoteHome)PortableRemoteObject.narrow(obj,
          CustomerFacadeRemoteHome.class)).create();
    }
    ...
  4. Change the testCreateCustomer and testGetLastName methods as follows:
    ...
    public void testCreateCustomer() throws Exception {
      System.out.println("PK: " + customerFacade.createCustomer("Foo","Bar"));
    }
    
    public void testGetLastName() throws Exception {
      long id = customerFacade.createCustomer("Joe", "User");
      assertEquals(1, getLastName("name").length());
    }
    ...
  5. Delete the rest of the testMethodName methods.
  6. Right-click the Test Libraries node in the Projects window and choose Add JAR/Folder. Add the appserv-rt.jar file from your application server's lib directory to the test classpath.
  7. Press Alt-Shift-F to generate any needed import statements.
  8. Right-click the CustomerModule project and choose Deploy Project. The IDE deploys the project.
  9. With the CustomerModule project selected in the Projects window, choose Run > Test "CustomerModule". The IDE compiles and runs the tests and displays the following output in the Output window.
    init:
    deps-jar:
    compile:
    Compiling 1 source file to C:\new\CustomerModule\build\test\classes
    compile-test:
    03-Aug-2005 12:42:11 com.sun.corba.ee.spi.logging.LogWrapperBase doLog
    INFO: "IOP00710299: (INTERNAL) Successfully created IIOP listener on the specified host/port: all
    interfaces/1502"
    PK: 1123065661713
    Testsuite: org.bank.CustomerFacadeBeanTest
    Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 3.855 sec
    
    ------------- Standard Output ---------------
    PK: 1123065661713
    ------------- ---------------- ---------------
    ------------- Standard Error -----------------
    03-Aug-2005 12:42:11 com.sun.corba.ee.spi.logging.LogWrapperBase doLog
    INFO: "IOP00710299: (INTERNAL) Successfully created IIOP listener on the specified host/port:
    all interfaces/1502"
    ------------- ---------------- ---------------
    test-report:
    test:
    BUILD SUCCESSFUL (total time: 6 seconds)
    

↑返回目录
前一篇: Exploring the NetBeans Visual Mobile Designer
后一篇: Getting Started with JMX Monitoring in NetBeans IDE 5.0