Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Online Training

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
 
Training Index

Writing Advanced Applications
Chapter 3 Continued: Bean-Managed Persistence and the JDBCTM Platform

[<<BACK] [CONTENTS] [NEXT>>]

There might be times when you want to override container-managed persistence and implement entity or session Bean methods to use the SQL commands you provide. This type of Bean-managed persistence can be useful if you need to improve performance or map data in multiple Beans to one row in a database table.

This section shows you how to convert the RegistrationBean.java class to access the database with the JDBCTM PreparedStatement class.


Connect to Database

This version of the RegistrationBean.java class establishes a connection to the database by instantiating a static Driver class and providing the getConnection method.

The getConnection method queries the static DriverManager class for a registered database driver that matches the Uniform Resource Locator (URL) . In this case, the URL is weblogic.jdbc.jts.Driver.

//Create static instance of database driver
static {
  new weblogic.jdbc.jts.Driver();
}

//Get registered driver from static instance
public Connection getConnection() throws SQLException{
  return DriverManager.getConnection(
                        "jdbc:weblogic:jts:ejbPool");
  }

Create Method

The ejbCreate method assigns values to data member variables, gets a connection to the database, and creates an instance of the java.sql.PreparedStatement class to execute the SQL statement for writing the data to the registration table in the database.

A PreparedStatement object is created from a SQL statement which is sent to the database and precompiled before any data is sent. You call the appropriate setXXX statements on the PreparedStatement object to send the data. Keeping the PreparedStatement and Connection objects has private instance variables greatly reduces overhead because the SQL statement does not have to be compiled everytime data is sent.

The last thing the ejbCreate method does is create a primary key class with the user Id, and return it to the container.

public RegistrationPK ejbCreate(String theuser, 
				String password, 
				String emailaddress, 
				String creditcard) 
	throws CreateException, RemoteException {

  this.theuser=theuser;
  this.password=password;
  this.emailaddress=emailaddress;
  this.creditcard=creditcard;
  this.balance=0;

  try {
    con=getConnection();
    ps=con.prepareStatement("insert into registration (
			     theuser, password, 
			     emailaddress, creditcard, 
		  	     balance) values (
			     ?, ?, ?, ?, ?)");
    ps.setString(1, theuser);
    ps.setString(2, password);
    ps.setString(3, emailaddress);
    ps.setString(4, creditcard);
    ps.setDouble(5, balance);
    if (ps.executeUpdate() != 1) {
      throw new CreateException (
                  "JDBC did not create a row");
    }
    RegistrationPK primaryKey = new RegistrationPK();
    primaryKey.theuser = theuser;
    return primaryKey;
    } catch (CreateException ce) {
      throw ce;
    } catch (SQLException sqe) {
      throw new CreateException (sqe.getMessage());
    } finally {
      try {
         ps.close();
      } catch (Exception ignore) {}
      try {
         con.close();
      } catch (Exception ignore) {}
    }
}

Load Method

This method gets the primary key from the entity context and passes it to the refresh method which loads the data.
  public void ejbLoad() throws RemoteException {
    try {
      refresh((RegistrationPK) ctx.getPrimaryKey());
    }
    catch (FinderException fe) {
      throw new RemoteException (fe.getMessage());
    }
  }

Refresh Method

The refresh method is programmer-supplied code to load the data from the database. It checks the primary key value, gets a connection to the database, and creates a PreparedStatement object for querying the database for the user specified in the primary key.

Data is read from the database into a ResultSet and assigned to the global member variables so the RegistrationBean has the most up-to-date information for the user.

private void refresh(RegistrationPK pk)
             throws FinderException, RemoteException {

  if (pk == null) {
    throw new RemoteException ("primary key 
				cannot be null");
  }
  Connection con = null;
  PreparedStatement ps = null;
  try {
     con=getConnection();
     ps=con.prepareStatement("select password, 
		emailaddress, creditcard, 
		balance from registration 
		where theuser = ?");
     ps.setString(1, pk.theuser);
     ps.executeQuery();
     ResultSet rs = ps.getResultSet();
     if (rs.next()) {
       theuser = pk.theuser;
       password = rs.getString(1);
       emailaddress = rs.getString(2);
       creditcard = rs.getString(3);
       balance = rs.getDouble(4);
     }
     else {
        throw new FinderException (
                    "Refresh: Registration ("
                    + pk.theuser + ") not found");
     }
  }
  catch (SQLException sqe) {
     throw new RemoteException (sqe.getMessage());
  }
  finally {
     try {
        ps.close();
     }
     catch (Exception ignore) {}
     try {
        con.close();
     }
     catch (Exception ignore) {}
  }
}

Store Method

This method gets a database connection and creates a PreparedStatement to update the database.
public void ejbStore() throws RemoteException {
  Connection con = null;
  PreparedStatement ps = null;
  try {
     con = getConnection();
     ps = con.prepareStatement("update registration 
				set password = ?, 
				emailaddress = ?, 
				creditcard = ?, 
				balance = ? 
				where theuser = ?");
     ps.setString(1, password);
     ps.setString(2, emailaddress);
     ps.setString(3, creditcard);
     ps.setDouble(4, balance);
     ps.setString(5, theuser);
     int i = ps.executeUpdate();
     if (i == 0) {
       throw new RemoteException (
                   "ejbStore: Registration (
		   " + theuser + ") not updated");
     }
  } catch (RemoteException re) {
       throw re;
  } catch (SQLException sqe) {
       throw new RemoteException (sqe.getMessage());
  } finally {
    try {
       ps.close();
    } catch (Exception ignore) {}
     try {
        con.close();
     }
     catch (Exception ignore) {}
  }
}

Find Method

The ejbFindByPrimaryKey method matches the signature of the FindByPrimaryKey method in the RegistrationHome interface. It calls the refresh method to get or refresh the user data for the user specified by the primary key.

The container-managed persistence version of RegistrationBean does not implement this method because the container handles getting and refreshing the user data.

public RegistrationPK ejbFindByPrimaryKey(
		RegistrationPK pk)
           	throws FinderException, 
           	RemoteException {

  if ((pk == null) || (pk.theuser == null)) {
     throw new FinderException ("primary key 
				 cannot be null");
  }
  refresh(pk);
  return pk;
}

[TOP]


[ This page was updated: 13-Oct-99 ]

Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-99 Sun Microsystems, Inc.
All Rights Reserved. Legal Terms. Privacy Policy.