Java .

Java Container Managed Entity EJB

Note: This Example Uses J2EE 1.3

The Remote Interface - CmDvd.java

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

public interface CmDvd extends EJBObject {   
 
    public void setTitle(String newTitle)
        throws RemoteException;
    
    public void setFormat(String newFormat)
        throws RemoteException;       
    
    public String getIsbn()
        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 - CmDvdHome.java

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

public interface CmDvdHome extends EJBHome {

    public CmDvd create(String isbn, String title, String format)
        throws RemoteException, CreateException;
    
    public CmDvd 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;  
    
    public Collection findAllTitles()
        throws FinderException, RemoteException;      

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

The Enterprise Bean Class - CmDvdBean.java

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

public abstract class CmDvdBean implements EntityBean {

    private EntityContext context;
    /*bean state fields*/
    private String isbn;  //the primary key
    private String title;
    private String format;    
    
    /*methods in remote interface, access state fields*/ 
    
    public abstract void setIsbn(String isbn);
    public abstract void setTitle(String title);
    public abstract void setFormat(String format);
 
    public abstract String getIsbn();    
    public abstract String getTitle();
    public abstract String getFormat(); 
    
    public String getAsString() {
       return("dvd = isbn: " + getIsbn() + 
              " title: " + getTitle() + 
              " format: " + getFormat());          
    }     
    
    
    /*methods in home interface, use table(s)  */    
    
    public String ejbCreate(String isbn, 
                            String title, 
                            String format) 
                            throws CreateException
    {
       setIsbn(isbn);
       setTitle(title);
       setFormat(format);

       return isbn;
    }

    /* methods necessary in an entity bean, in 
       cm-ejb db calls are handled by the container */     
   
   public void ejbRemove() 
   {} 

   public void setEntityContext(EntityContext entityContext) 
   {
       this.context = entityContext;
   }

   public void unsetEntityContext() 
   {
       this.context = null;
   }

   public void ejbActivate() { }

   public void ejbPassivate() { }

   public void ejbLoad() { }
   
   public void ejbStore() { }

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

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

ejb-jar.xml

note: this examples illustrates a like statement. This, however, does not seem to work - please see notes at the bottom of the page.

A Client Application - CmDvdClient.java

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

public class CmDvdClient {

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

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

           CmDvd 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 = (CmDvd)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()) {
              CmDvd dvd = (CmDvd)iterator.next();
              System.out.println("in bis loop: " + dvd.getAsString());
           } 
           
           CmDvd rlr = null;
           dvdCheck = dvdHome.findByIsbn("076783738X");
           if (dvdCheck.isEmpty()) {
              rlr = dvdHome.create("076783738X", 
                                   "Run Lola Run",        
                                   "WS-FS");      
           }         
             
           CmDvd pf = null;
           dvdCheck = dvdHome.findByIsbn("0780634551");
           if (dvdCheck.isEmpty()) {
               pf = dvdHome.create("0780634551", 
                                   "Pink Flamingos",
                                   "WS   ");
           }  
           
           CmDvd sil = null;
           dvdCheck = dvdHome.findByIsbn("0788818937");
           if (dvdCheck.isEmpty()) {
               sil = dvdHome.create("0788818937", 
                                    "Shakespeare in Love",
                                    "WS   ");
           }       
           
           CmDvd tpb = null;
           dvdCheck = dvdHome.findByIsbn("0792850769");
           if (dvdCheck.isEmpty()) {
               tpb = dvdHome.create("0792850769", 
                                    "The Princess Bride",  
                                    "WS   ");     
           }                 
           
           System.out.println("before findByTitleWith");
           collection = dvdHome.findByTitleWith("in");
           iterator=collection.iterator();
           while (iterator.hasNext()) {
              CmDvd dvd = (CmDvd)iterator.next();
              System.out.println("in like loop: " + dvd.getAsString());
           }         
           
           System.out.println("before findAllTitles");  
           collection = dvdHome.findAllTitles(); 
           iterator=collection.iterator();
           while (iterator.hasNext()) {
              CmDvd dvd = (CmDvd)iterator.next();
              System.out.println("in all title 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
before findByTitleWith
before findAllTitles
in all title loop: dvd = isbn: 076783738X 
  title: Run Lola Run format: WS-FS
in all title loop: dvd = isbn: 078063344X 
  title: Best in Show format: WS
in all title loop: dvd = isbn: 0780634551 
  title: Pink Flamingos format: WS
in all title loop: dvd = isbn: 0788818937 
  title: Shakespeare in Love format: WS
in all title loop: dvd = isbn: 0792850769 
  title: The Princess Bride format: WS

application-client.xml

Notes

When using container-managed entity beans you must code EJB-QL to define your custom sql queries. There are a few things that you can not do in EJB-QL, which can be done in SQL. As shown in the example, passing of parameters into a like statement does not seem to work. It is possible that you can do this, and I just do not know how to code it.

You can not directly incorporate anything db specific into EJB-QL, such as Oracle's PL/SQL.

As is detailed in Enterprise Java Beans - by Monson-Haefel (reference 3) on pages 250-252, there is no "Order By" clause in EJB-QL. Also noted is lack of function support, so there is no Count(), Max(), Min(), etc. Finally, there is no support for java.util.Date.

One thing I did not show in the examples is cm-ejb's ability to handle the relationships between tables. Because the cm-ejb is managing all of the tables used with it, cm-ejb needs to know how your tables are tied together. Using a fairly straight-forward scheme you give the fields in one table that tie to fields in another table. You also indicate what kind of relationship (1:1, 1:n, n:1, n:1) the tables have. You may also indicate wether a row should be deleted if the row it is tied to in another table is deleted.

So, if you like the idea of the EJB handing most of the db work, you should be a fan of cm-ejb. On the other hand, if you are a big sql fan who likes to "code their own sql" you might be somewhat disappointed with the control you have over container-managed entity beans.

Incidentally, depending on your bean server, you may be able to override some or all of the sql that is generated. You can also add some jdbc directly into your modules for some calls, but the mixing of methodologies could become confusing.

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 Comments are left by visitors to FluffyCat.com and may or may not be accurate.
Comment by Larry on 2012-08-27 Rate this Comment

I was also using the Sun RI J2EE server, and you are correct - it does not work. Further down in my notes section I do discuss this. Sorry I gave you some hope there.

(from the notes section)

"When using container-managed entity beans you must code EJB-QL to define your custom sql queries. There are a few things that you can not do in EJB-QL, which can be done in SQL. As shown in the example, passing of parameters into a like statement does not seem to work. It's possible that you can do this, and I just don't know how to code it."

I did want to show this as an example of something I couldn't do. I'll put a comment right in the java to make things more clear.

I do like EJBs, they are all teriffic. Except the CMB. Maybe it isn't up to the others - or maybe it is that I like to write the SQL myself.

Comment by archive on 2006-04-27 Rate this Comment

Just a quick question about which J2EE server you succesfully have deployed your CMP entity EJB example on your website in?

I'm sofar just working with the Sun RI J2EE server, and are having major difficulties in using the "LIKE" operator in EJB-QL, and I stumbled over your code where you use a variable '?1' along with '%' wildcards (See below). This will not run in the Sun RI server, and looking at some of the mail lists many others have had the same problem...

 
Sign in to comment on Java Container Managed Entity EJB.