Java .

Java Bean Managed Entity EJB

Note: This Example Uses J2EE 1.3

The Remote Interface - Dvd.java

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Dvd extends EJBObject {   
 
    public void setTitle(String newTitle)
        throws RemoteException;
    
    public void setFormat(String newFormat)
        throws RemoteException;       
    
    public String getTitle()
        throws RemoteException;

    public String getFormat()
        throws RemoteException;
    
    public String getAsString()
        throws RemoteException;
}
To download source right-click here and "Save As...".

The Home Interface - DvdHome.java

import java.util.Collection;
import java.rmi.RemoteException;
import javax.ejb.*;

public interface DvdHome extends EJBHome {

    public Dvd create(String isbn, String title, String format)
        throws RemoteException, CreateException;
    
    public Dvd findByPrimaryKey(String isbn) 
        throws FinderException, RemoteException;

    public Collection findByIsbn(String isbn) 
        throws FinderException, RemoteException;        
    
    public Collection findByTitle(String title)
        throws FinderException, RemoteException;
    
    public Collection findByTitleWith(String title)
        throws FinderException, RemoteException;    

}
To download source right-click here and "Save As...".

The Enterprise Bean Class - DvdBean.java

import java.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
import javax.sql.*;

public class DvdBean implements EntityBean {

    private EntityContext entityContext;
    private Connection connection;
    private String dbName = "java:comp/env/jdbc/DvdDB";
    /*bean state fields*/
    private String isbn;  //the primary key
    private String title;
    private String format;    
    
    /*methods in remote interface, access state fields*/ 
    
    public void setTitle(String newTitle) {
       this.title = newTitle;
    }
    
    public void setFormat(String newFormat) {
       this.format = newFormat;
    }    
 
    public String getTitle() {
        return title;
    }
 
    public String getFormat() {
       return format;
    }
    
    public String getAsString() {
       return("dvd = isbn: " + isbn + 
              " title: " + title + 
              " format: " + format);          
    }     
    
    
    /*methods in home interface, use table(s)  */    
    
    public String ejbCreate(String isbn, 
                            String title, 
                            String format) throws CreateException 
    {
       try 
       {
          dbInsertRow(isbn, title, format);
       } catch (Exception exception) {
         throw new EJBException(
           "ejbCreate():dbInsertRowCalled with isbn: " + isbn + 
           " title: " + title + 
           " format: " + format + 
           " exception: " + exception.getMessage());}

       this.isbn = isbn;
       this.title = title;
       this.format = format;

       return isbn;
    }

   public String ejbFindByPrimaryKey(String primaryKey) 
     throws FinderException {
      boolean result;
      
      try 
      {
         result = dbSelectByPrimaryKey(primaryKey);
      } catch (Exception exception) {
        throw new EJBException(
        "ejbFindByPrimaryKey(): after calling dbSelectByPrimaryKey " + 
        exception.getMessage());}
      
      if (result) {
         return primaryKey;
      } else {
         throw new ObjectNotFoundException (
           "ejbFindByPrimaryKey(): Row for id " + primaryKey + 
           " not found.");
      }
   }

   //differs from ejbFindByPrimaryKey in that it returns a collection, 
   //  and so can return a null set 
   public Collection ejbFindByIsbn(String primaryKey) 
     throws FinderException {
      Collection result;
      
      try {
         result = dbSelectByIsbn(primaryKey);
      } catch (Exception exception) {
        throw new EJBException(
          "ejbCheckForPrimaryKey(): after calling dbSelectByIsbn " + 
          exception.getMessage());}
      
      return result;
   } 
   
   public Collection ejbFindByTitle(String title) 
     throws FinderException {
      Collection result;
      try {
         result = dbSelectByTitle(title);
      } catch (Exception exception) {
        throw new EJBException(
          "ejbFindByTitle: after calling dbSelectByTitle() " + 
          exception.getMessage());}
      return result;
   }
   
   public Collection ejbFindByTitleWith(String title) 
     throws FinderException {
      Collection result;
      try 
      {
         result = dbSelectByTitleWith(title);
      } catch (Exception exception) {
        throw new EJBException(
          "ejbFindByTitleWith: after calling dbSelectTitleWith() " + 
          exception.getMessage());}
      return result;
   }   
   

    /*methods necessary in an entity bean */     
   
   public void ejbRemove() 
   {
      try 
      {
         dbDeleteRow(isbn);
      } catch (Exception exception) {
        throw new EJBException(
        "ejbRemove(): after calling dbDeleteRow() " + 
        exception.getMessage());}
   } 

   public void setEntityContext(EntityContext entityContext) {
      this.entityContext = entityContext;
      try {
         dbMakeConnection();
      } catch (Exception exception) {
        throw new EJBException(
          "setEntityContext(): after calling dbMakeConnection() " +
          exception.getMessage());}
   }

   public void unsetEntityContext() {
      try {
         connection.close();
      } catch (SQLException exception) {
        throw new EJBException(
          "unsetEntityContext(): closing connection" + 
          exception.getMessage());}
   }

   public void ejbActivate() {
      isbn = (String)entityContext.getPrimaryKey();
   }

   public void ejbPassivate() {

      isbn = null;
   }

   public void ejbLoad() {
      try {
         dbLoadRow();
       } catch (Exception exception) {
         throw new EJBException(
           "ejbLoad():dbLoadRow called using this.isbn: " + 
           this.isbn +
           " exception " + exception.getMessage());}
   }
   
   public void ejbStore() {
      try {
         dbStoreRow();
       } catch (Exception exception) {
         throw new EJBException("ejbStore(): " +  
         exception.getMessage());
       }
   }

   public void ejbPostCreate(String isbn, 
                             String title, 
                             String format) {
   }


   /*db methods*/

   private void dbMakeConnection() 
     throws NamingException, SQLException {
      InitialContext initialContext = new InitialContext();
      DataSource dataSource = 
        (DataSource)initialContext.lookup(dbName);
      connection =  dataSource.getConnection();
   }

   private void dbInsertRow (String isbn, 
                             String title, 
                             String format) throws SQLException {
      String insertStatement = "insert into dvd values ( ? , ? , ? )";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(insertStatement);

      preparedStatement.setString(1, isbn);
      preparedStatement.setString(2, title);
      preparedStatement.setString(3, format);

      preparedStatement.executeUpdate();
      preparedStatement.close();
   }

   private void dbDeleteRow(String isbn) throws SQLException {
      String deleteStatement = "delete from dvd where isbn = ? ";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(deleteStatement);

      preparedStatement.setString(1, isbn);
      preparedStatement.executeUpdate();
      preparedStatement.close();
   }

   private boolean dbSelectByPrimaryKey(String primaryKey) 
     throws SQLException {
      String selectStatement = 
        "select isbn from dvd where isbn = ? ";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(selectStatement);
      preparedStatement.setString(1, primaryKey);

      ResultSet resultSet = preparedStatement.executeQuery();
      boolean result = resultSet.next();
      
      preparedStatement.close();
      return result;
   }
   
   private Collection dbSelectByIsbn(String isbnIn) 
     throws SQLException {
      String selectStatement = "select isbn from dvd where isbn = ? ";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(selectStatement);
      preparedStatement.setString(1, isbnIn);
      
      ResultSet resultSet = preparedStatement.executeQuery();
      
      ArrayList arrayList = new ArrayList();
      while (resultSet.next()) {
         String isbn = resultSet.getString(1);
         arrayList.add(isbn);
      }
      
      preparedStatement.close();
      return arrayList;
   }   

   private Collection dbSelectByTitle(String title) 
     throws SQLException {
      String selectStatement = 
        "select isbn from dvd where title = ? ";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(selectStatement);
      preparedStatement.setString(1, title);
      
      ResultSet resultSet = preparedStatement.executeQuery();

      ArrayList arrayList = new ArrayList();
      while (resultSet.next()) {
         String isbn = resultSet.getString(1);
         arrayList.add(isbn);
      }

      preparedStatement.close();
      return arrayList;
   }

   private Collection dbSelectByTitleWith(String title) 
     throws SQLException {
      String selectStatement = 
        "select isbn from dvd where title like ? ";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(selectStatement);
      preparedStatement.setString(1, "%" + title + "%");

      ResultSet resultSet = preparedStatement.executeQuery();
      
      ArrayList arrayList = new ArrayList();
      while (resultSet.next()) {
         String isbn = resultSet.getString("isbn");
         arrayList.add(isbn);
      }

      preparedStatement.close();
      return arrayList;
   }   
   
   private void dbLoadRow() throws SQLException { 
      String selectStatement = 
        "select title, format from dvd where isbn = ? ";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(selectStatement);
      preparedStatement.setString(1, this.isbn);

      ResultSet resultSet = preparedStatement.executeQuery();

      if (resultSet.next()) {
         this.title = resultSet.getString(1);
         this.format = resultSet.getString(2);
         preparedStatement.close();
      } else {
         preparedStatement.close();
         throw new NoSuchEntityException(
           "dbLoadRow(): Row for isbn " + isbn + 
           " not found in database.");
      }
   }

   private void dbStoreRow() throws SQLException {
      String updateStatement = 
        "update dvd set title =  ? , format = ? where isbn = ?";
      PreparedStatement preparedStatement = 
        connection.prepareStatement(updateStatement);

      preparedStatement.setString(1, title);
      preparedStatement.setString(2, format);
      preparedStatement.setString(3, isbn);
      int rowCount = preparedStatement.executeUpdate();
      preparedStatement.close();

      if (rowCount == 0) {
         throw new EJBException(
           "dbStoreRow(): Storing row for isbn " + isbn + " failed.");
      }
   }

}  
To download source right-click here and "Save As...".

ejb-jar.xml

A Client Application - DvdClient.java

import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class DvdClient {

   public static void main(String[] args) 
   {
       try {
           Context initialContext = new InitialContext();
           Object initialContextObject = 
             initialContext.lookup("java:comp/env/ejb/SimpleDvd");

           DvdHome dvdHome = 
             (DvdHome)PortableRemoteObject.narrow(initialContextObject, 
                                                  DvdHome.class);

           Dvd bis;
           Collection dvdCheck;
           Iterator dvdCheckIterator;
           //Check to see if this pk already exists. 
           //Maybe not an efficent way to do things, 
           //  but an interesting example.
           dvdCheck = dvdHome.findByIsbn("078063344X");
           if (dvdCheck.isEmpty()) {
              bis = 
            	dvdHome.create("078063344X", "Best of Show", "WS   ");
           } else {
              dvdCheckIterator = dvdCheck.iterator();
              bis = (Dvd)dvdCheckIterator.next();
           }  
           
           System.out.println("after create: " + bis.getAsString());  
           bis.setTitle("Best in Show");  
           System.out.println("after change title: " + 
                              bis.getAsString());

           Collection collection = dvdHome.findByTitle("Best in Show");
           Iterator iterator=collection.iterator();
           while (iterator.hasNext()) {
              Dvd dvd = (Dvd)iterator.next();
              System.out.println("in bis loop: " + dvd.getAsString());
           } 
           
           Dvd rlr = null;
           dvdCheck = dvdHome.findByIsbn("076783738X");
           if (dvdCheck.isEmpty()) {
              rlr = dvdHome.create("076783738X", 
                                   "Run Lola Run",
                                   "WS-FS");
           }
             
           Dvd pf = null;
           dvdCheck = dvdHome.findByIsbn("0780634551");
           if (dvdCheck.isEmpty()) {
               pf = dvdHome.create("0780634551", 
                                   "Pink Flamingos",      
                                    "WS   ");
           }  
           
           Dvd sil = null;
           dvdCheck = dvdHome.findByIsbn("0788818937");
           if (dvdCheck.isEmpty()) {
               sil = dvdHome.create("0788818937", 
                                    "Shakespeare in Love", 
                                    "WS   ");
           }       
           
           Dvd tpb = null;
           dvdCheck = dvdHome.findByIsbn("0792850769");
           if (dvdCheck.isEmpty())
           {
               tpb = dvdHome.create("0792850769", 
                                    "The Princess Bride",  
                                    "WS   ");     
           } 
           
           collection = dvdHome.findByTitleWith("in");
           iterator=collection.iterator();
           while (iterator.hasNext()) {
              Dvd dvd = (Dvd)iterator.next();
              System.out.println("in like loop: " + dvd.getAsString());
           }

           if (bis != null) {bis.remove();}
             //note: will remove from table
           if (rlr != null) {rlr.remove();}
             //note: will remove from table only if we created rlr 
             //  in this run
           if (pf  != null) {pf.remove();}
             //note: will remove from table only if we created pf 
             //  in this run  
           if (sil != null) {sil.remove();}
             //note: will remove from table only if we created sil
             //  in this run
           if (tpb != null) {tpb.remove();}
             //note: will remove from table only if we created tpb 
             //  in this run

       } catch (Exception exception) {
           System.err.println("Caught an exception." );
           exception.printStackTrace();
       }
   } 
} 

To download source right-click here and "Save As...".

DvdClient's output

           
after create: dvd = isbn: 078063344X 
  title: Best of Show format: WS
after change title: dvd = isbn: 078063344X 
  title: Best in Show format: WS
in bis loop: dvd = isbn: 078063344X 
  title: Best in Show format: WS
in like loop: dvd = isbn: 0780634551 
  title: Pink Flamingos format: WS
in like loop: dvd = isbn: 0788818937 
  title: Shakespeare in Love format: WS
in like loop: dvd = isbn: 078063344X 
  title: Best in Show format: WS
in like loop: dvd = isbn: 0792850769 
  title: The Princess Bride format: WS

application-client.xml

References


online
J2EE (TM) 1.3 Tutorial from Sun
SQL at www.FluffyCat.com
Books
Enterprise Java Beans by Richard Monson-Haefel
Mastering Enterprise JavaBeans by Ed Roman
Comments
Sign in to be the first to comment on Java Bean Managed Entity EJB.