5.4 Enterprise Java Beans

Enterprise beans son componentes de J2EE que implementan la tecnología Enterprise JavaBeans (EJB).

Enterprise beans corren dentro de un EJB container, un runtime environment dentro del Application Server.

Cuándo emplear Enterprise Beans

Se debe considerar el uso de enterprise beans si la aplicación presenta alguno de los siguientes requerimientos:

 

Tipos de Enterprise Beans

 

Table 23-1 Enterprise Bean Types Enterprise Bean Type Purpose
Session

Realiza una tarea para un cliente, implementa un web service

Tipos

  • Un stateless session bean no mantiene un estado conversacional con el cliente
  • En un stateful session bean, las instancias de las variables representan el estado de una sesión
Entity

Representa un objeto que existe en almacenamiento persistente

  • Persistence
  • Shared Access
  • Primary Key
  • Relationships

Tipos

  • Container-managed persistence (CMP)
  • Bean-managed persistence (BMP)
Message-Driven Actua como un listener del Java Message Service API, procesando mensajes de manera asíncrona

 

Para desarrollar una enterprise bean, se deben proveer los siguientes archivos:

 

Descripción de clases e interfaces

Table 23-2 Naming Conventions for Enterprise Beans  Item Syntax Example
Enterprise bean name (DD)     < name >Bean AccountBean
EJB JAR display name (DD)     < name >JAR AccountJAR
Enterprise bean class business and life-cycle implementation < name >Bean AccountBean
Home interface life-cycle outside container javax.ejb.EJBHome < name >Home AccountHome
Remote interface business outside container javax.ejb.EJBObject < name > Account
Local home interface life-cycle inside containe javax.ejb.EJBLocalHome < name >LocalHome AccountLocalHome
Local interface business inside container javax.ejb.EJBLocalObject < name > Local AccountLocal
Abstract schema (DD)     < name > Account
DD deployment descriptor.

 

Session Bean

   1:package com.titan.travelagent;
   2:
   3:import com.titan.cabin.CabinRemote;
   4:import com.titan.cabin.CabinHomeRemote;
   5:import java.rmi.RemoteException;
   6:import javax.naming.InitialContext;
   7:import javax.naming.Context;
   8:import javax.ejb.EJBException;
   9:import java.util.Properties;
  10:import java.util.Vector;
  11:
  12:public class TravelAgentBean implements javax.ejb.SessionBean 
  13:{
  14:
  15:   public void ejbCreate() 
  16:   {
  17:      // Do nothing.
  18:   }
  19:
  20:   public String [] listCabins(int shipID, int bedCount) 
  21:   {
  22:      try 
  23:      {
  24:         javax.naming.Context jndiContext = new InitialContext();
  25:         Object obj = 
  26:            jndiContext.lookup("java:comp/env/ejb/CabinHomeRemote");
  27:
  28:
  29:         CabinHomeRemote home = (CabinHomeRemote)
  30:            javax.rmi.PortableRemoteObject.narrow(obj,CabinHomeRemote.class);
  31:
  32:         Vector vect = new Vector();
  33:         for (int i = 1; ; i++) 
  34:         {
  35:            Integer pk = new Integer(i);
  36:            CabinRemote cabin = null;
  37:            try 
  38:            {
  39:               cabin = home.findByPrimaryKey(pk);
  40:            } 
  41:            catch(javax.ejb.FinderException fe) 
  42:            {
  43:               System.out.println("Caught exception: "+fe.getMessage()+" for pk="+i); 
  44:               break;
  45:            }
  46:            // Check to see if the bed count and ship ID match.
  47:            if (cabin != null &&
  48:                cabin.getShipId() == shipID && 
  49:                cabin.getBedCount() == bedCount) 
  50:            {
  51:               String details = 
  52:                  i+","+cabin.getName()+","+cabin.getDeckLevel();
  53:               vect.addElement(details);
  54:            }
  55:         }
  56:        
  57:         String [] list = new String[vect.size()];
  58:         vect.copyInto(list);
  59:         return list;
  60:       
  61:      } 
  62:      catch(Exception e) 
  63:      {
  64:         throw new EJBException(e);
  65:      }    
  66:   }
  67:
  68:   public void ejbRemove(){}
  69:   public void ejbActivate(){}
  70:   public void ejbPassivate(){}
  71:   public void setSessionContext(javax.ejb.SessionContext cntx){}
  72:}
 
   1:package com.titan.travelagent;
   2:
   3:import java.rmi.RemoteException;
   4:import javax.ejb.CreateException;
   5:
   6:public interface TravelAgentHomeRemote extends javax.ejb.EJBHome {
   7:
   8:    public TravelAgentRemote create()
   9:        throws RemoteException, CreateException;
  10:
  11:}
 
   1:package com.titan.travelagent;
   2:
   3:import java.rmi.RemoteException;
   4:import javax.ejb.FinderException;
   5:
   6:public interface TravelAgentRemote extends javax.ejb.EJBObject {
   7:
   8:    // String elements follow the format "id, name, deck level"
   9:    public String [] listCabins(int shipID, int bedCount)
  10:        throws RemoteException;
  11:
  12:}
 

Entity Bean

   1:package com.titan.cabin;
   2:
   3:import javax.ejb.EntityContext;
   4:import javax.ejb.CreateException;
   5:
   6:public abstract class CabinBean 
   7:   implements javax.ejb.EntityBean 
   8:{
   9:
  10:   public Integer ejbCreate(Integer id) 
             throws CreateException
  11:   {
  12:      this.setId(id);
  13:      return null;
  14:   }
  15:   public void ejbPostCreate(Integer id)
  16:   {
  17:   }
  18:   
  19:   public abstract void setId(Integer id);
  20:   public abstract Integer getId();
  21: 
  22:   public abstract void setShipId(int ship);
  23:   public abstract int getShipId( );
  24:
  25:   public abstract void setName(String name);
  26:   public abstract String getName( );
  27:
  28:   public abstract void setBedCount(int count);
  29:   public abstract int getBedCount();
  30:
  31:   public abstract void setDeckLevel(int level);
  32:   public abstract int getDeckLevel();
  33:
  34:   public void setEntityContext(EntityContext ctx) 
  35:   {
  36:      // Not implemented.
  37:   }
  38:   public void unsetEntityContext() 
  39:   {
  40:      // Not implemented.
  41:   }
  42:   public void ejbActivate() 
  43:   {
  44:      // Not implemented.
  45:   }
  46:   public void ejbPassivate() 
  47:   {
  48:      // Not implemented.
  49:   }
  50:   public void ejbLoad() 
  51:   {
  52:      // Not implemented.
  53:   }
  54:   public void ejbStore() 
  55:   {
  56:      // Not implemented.
  57:   }
  58:   public void ejbRemove() 
  59:   {
  60:      // Not implemented.
  61:   }
  62:}
   1:package com.titan.cabin;
   2:
   3:import java.rmi.RemoteException;
   4:import javax.ejb.CreateException;
   5:import javax.ejb.FinderException;
   6:
   7:public interface CabinHomeRemote extends javax.ejb.EJBHome 
   8:{
   9:   public CabinRemote create(Integer id)
  10:      throws CreateException, RemoteException;
  11:   
  12:   public CabinRemote findByPrimaryKey(Integer pk)
  13:      throws FinderException, RemoteException;
  14:}
 
   1:package com.titan.cabin;
   2:
   3:import java.rmi.RemoteException;
   4:
   5:public interface CabinRemote extends javax.ejb.EJBObject 
   6:{
   7:   public String getName() throws RemoteException;
   8:   public void setName(String str) throws RemoteException;
   9:   public int getDeckLevel() throws RemoteException;
  10:   public void setDeckLevel(int level) throws RemoteException;
  11:   public int getShipId() throws RemoteException;
  12:   public void setShipId(int sp) throws RemoteException;
  13:   public int getBedCount() throws RemoteException;
  14:   public void setBedCount(int bc) throws RemoteException; 
  15:}
 

Ejemplo y Descriptores

   1:package com.titan.clients;
   2:
   3:import com.titan.travelagent.TravelAgentHomeRemote;
   4:import com.titan.travelagent.TravelAgentRemote;
   5:
   6:import javax.naming.InitialContext;
   7:import javax.naming.Context;
   8:import javax.naming.NamingException;
   9:import javax.ejb.CreateException;
  10:import javax.rmi.PortableRemoteObject;
  11:
  12:import java.rmi.RemoteException;
  13:
  14:public class Client_3 
  15:{
  16:   public static int SHIP_ID = 1;
  17:   public static int BED_COUNT = 3;
  18:
  19:   public static void main(String [] args) 
  20:   {
  21:      try 
  22:      {
  23:         Context jndiContext = getInitialContext();
  24:           
  25:         Object ref = jndiContext.lookup("TravelAgentHomeRemote");
  26:               
  27:         TravelAgentHomeRemote home = (TravelAgentHomeRemote)
  28:            PortableRemoteObject.narrow(ref,TravelAgentHomeRemote.class);
  29:        
  30:         TravelAgentRemote travelAgent = home.create();
  31:        
  32:         // Get a list of all cabins on ship 1 with a bed count of 3.
  33:         String list [] = travelAgent.listCabins(SHIP_ID,BED_COUNT);
  34:        
  35:         for(int i = 0; i < list.length; i++)
  36:         {
  37:            System.out.println(list[i]);
  38:         }
  39:      } 
  40:      catch(java.rmi.RemoteException re)
  41:      {
  42:         re.printStackTrace();
  43:      }
  44:      catch(Throwable t)
  45:      {
  46:         t.printStackTrace();
  47:      }
  48:   }
  49:
  50:   static public Context getInitialContext() throws Exception 
  51:   {
  52:      return new InitialContext();
  53:      /**** context initialized by jndi.properties file
  54:        java.util.Properties p = new java.util.Properties();
  55:p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
  56:        p.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
  57:        p.put(Context.PROVIDER_URL, "localhost:1099");
  58:        return new javax.naming.InitialContext(p);
  59:      */
  60:   }
  61:
  62:}
  63:
      
 
   1:<?xml version="1.0"?>
   2:
   3:<jboss>
   4:     <enterprise-beans>
   5:       <entity>
   6:         <ejb-name>CabinEJB</ejb-name>
   7:         <jndi-name>CabinHomeRemote</jndi-name>
   8:       </entity>
   9:       <session>
  10:         <ejb-name>TravelAgentEJB</ejb-name>
  11:         <jndi-name>TravelAgentHomeRemote</jndi-name>
  12:         <ejb-ref>
  13:           <ejb-ref-name>ejb/CabinHomeRemote</ejb-ref-name>
  14:           <jndi-name>CabinHomeRemote</jndi-name>
  15:         </ejb-ref>
  16:       </session>
  17:     </enterprise-beans>
  18:</jboss>
      
 
   1:<?xml version="1.0"?>
   2:
   3:<!DOCTYPE ejb-jar PUBLIC 
   4:"-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" 
   5:"http://java.sun.com/dtd/ejb-jar_2_0.dtd">
   6:
   7:<ejb-jar>
   8:
   9: <enterprise-beans>
  10:   <entity>
  11:      <ejb-name>CabinEJB</ejb-name>
  12:      <home>com.titan.cabin.CabinHomeRemote</home>
  13:      <remote>com.titan.cabin.CabinRemote</remote>
  14:      <ejb-class>com.titan.cabin.CabinBean</ejb-class>
  15:      <persistence-type>Container</persistence-type>
  16:      <prim-key-class>java.lang.Integer</prim-key-class>
  17:      <reentrant>False</reentrant>
  18:      <cmp-version>2.x</cmp-version>
  19:      <abstract-schema-name>Cabin</abstract-schema-name>
  20:      <cmp-field><field-name>id</field-name></cmp-field>
  21:      <cmp-field><field-name>name</field-name></cmp-field>
  22:      <cmp-field><field-name>deckLevel</field-name></cmp-field>
  23:      <cmp-field><field-name>shipId</field-name></cmp-field>
  24:      <cmp-field><field-name>bedCount</field-name></cmp-field>
  25:      <primkey-field>id</primkey-field>
  26:      <security-identity><use-caller-identity/></security-identity>
  27:   </entity>
  28:
  29:   <session>
  30:     <ejb-name>TravelAgentEJB</ejb-name>
  31:     <home>com.titan.travelagent.TravelAgentHomeRemote</home>
  32:     <remote>com.titan.travelagent.TravelAgentRemote</remote>
  33:     <ejb-class>com.titan.travelagent.TravelAgentBean</ejb-class>
  34:     <session-type>Stateless</session-type>
  35:     <transaction-type>Container</transaction-type>
  36:
  37:     <ejb-ref>
  38:       <ejb-ref-name>ejb/CabinHomeRemote</ejb-ref-name>  
  39:       <ejb-ref-type>Entity</ejb-ref-type>
  40:       <home>com.titan.cabin.CabinHomeRemote</home>
  41:       <remote>com.titan.cabin.CabinRemote</remote>
  42:     </ejb-ref>
  43:
  44:     <security-identity><use-caller-identity/></security-identity>
  45:
  46:  </session>
  47: </enterprise-beans>
  48:
  49: <assembly-descriptor>
  50:
  51:   <security-role>
  52:      <description>
  53:         This role represents everyone who is allowed full access to the beans.
  54:      </description>
  55:     <role-name>everyone</role-name>
  56:   </security-role>
  57:
  58:   <method-permission>
  59:     <role-name>everyone</role-name>
  60:     <method>
  61:       <ejb-name>CabinEJB</ejb-name>
  62:       <method-name>*</method-name>
  63:     </method>
  64:     <method>
  65:       <ejb-name>TravelAgentEJB</ejb-name>
  66:       <method-name>*</method-name>
  67:     </method>
  68:   </method-permission>
  69:
  70:   <container-transaction>
  71:     <method>
  72:       <ejb-name>CabinEJB</ejb-name>
  73:       <method-name>*</method-name>
  74:     </method>
  75:     <method>
  76:        <ejb-name>TravelAgentEJB</ejb-name>
  77:        <method-name>*</method-name>
  78:     </method>
  79:     <trans-attribute>Required</trans-attribute>
  80:   </container-transaction>
  81:
  82: </assembly-descriptor>
  83:
  84:</ejb-jar>
      
 

 

Desarrollando EJBs con JBuilder

Requerimientos

 

Configuring JBoss for MySQL


Existen 2 maneras de cambiar la base (en HSQL) por defecto de JBoss a MySQL:

  1. Sustituyendo el "DefaultDS" para que apunte ahora a una base en MySQL
    1. mysql-ds.xml
      • Copiar el archivo mysql-ds.xml localizado en [JBOSS_HOME]/docs/examples/jca al folder de deploy.
      • Modificarlo de manera que contenga los parametros de la base de datos para jboss (jbossdb en nuestro ejemplo) así como el nuevo nombre del data source:
          <jndi-name>DefaultDS</jndi-name>
      <connection-url>jdbc:mysql://localhost:9097/jbossdb</connection-url>
      <driver-class>com.mysql.jdbc.Driver</driver-class>
      <user-name>root</user-name>
      <password>lolo</password>
      • Eliminar el archivo hsqldb-ds.xml del directorio deploy.

     

    1. standardjaws.xml
      • Editar el archivo para cambiar el tipo de mapeo del datasource de Hypersonic SQL a mySQL.
      <datasource>java:/DefaultDS</datasource> 
      <type-mapping>mySQL</type-mapping> 
    2. JMS configuration descriptors
      • Eliminar el archivo hsqldb-jdbc2-service.xml del directorio deploy/jms.
      • Copiar el archivo mysql-jdbc2-service.xml del folder docs/example/jms al deploy/jms.
      • Editar el archivo mysql-jdbc2-service.xml y cambiar el datasource.
    3. <mbean code="org.jboss.mq.pm.jdbc2.PersistenceManager"
                     name="jboss.mq:service=PersistenceManager">
                     <depends optional-attribute-name="ConnectionManager">jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
                     <attribute name="SqlProperties">
    4. Instalar MySQL Java Connector, bajar el driver de MySQL y copiarlo al directorio lib del servidor.

     

  1. Creando un nuevo datasource ej: "MySqlDS"
    1. mysql-ds.xml
      • Copiar el archivo mysql-ds.xml localizado en [JBOSS_HOME]/docs/examples/jca al folder de deploy.
      • Modificarlo de manera que contenga los parametros de la base de datos para jboss (jbossdb en nuestro ejemplo) así como el nuevo nombre del data source:
          <jndi-name>MySqlDS</jndi-name>
      <connection-url>jdbc:mysql://localhost:9097/jbossdb</connection-url>
      <driver-class>com.mysql.jdbc.Driver</driver-class>
      <user-name>root</user-name>
      <password>lolo</password>
      • Eliminar el archivo hsqldb-ds.xml del directorio deploy.
    2. ejb-deployer.xml
      • Modificar el archivo de manera que emplee el Datasource de MySQL
            <!-- A persistence policy that persistes timers to a database -->
             <mbean code="org.jboss.ejb.txtimer.DatabasePersistencePolicy"          
                    name="jboss.ejb:service=EJBTimerService,persistencePolicy=database">
             <!-- DataSource JNDI name -->
             <depends optional-attribute-name="DataSource">jboss.jca:service=DataSourceBinding,name=MySqlDS</depends>
             <!-- The plugin that handles database persistence -->
             <attribute name="DatabasePersistencePlugin">org.jboss.ejb.txtimer.GeneralPurposeDatabasePersistencePlugin</attribute>
             </mbean>
    
    
    1. standardjaws.xml
      • Editar el archivo para cambiar el tipo de mapeo del datasource de Hypersonic SQL a mySQL.
      <datasource>java:/MySqlDS</datasource> 
      <type-mapping>mySQL</type-mapping> 
    2. JMS configuration descriptors
      • Eliminar el archivo hsqldb-jdbc2-service.xml del directorio deploy/jms.
      • Copiar el archivo mysql-jdbc2-service.xml del folder docs/example/jms al deploy/jms.
      • Editar el archivo mysql-jdbc2-service.xml y cambiar el datasource.
    3. <mbean code="org.jboss.mq.pm.jdbc2.PersistenceManager"
                     name="jboss.mq:service=PersistenceManager">
                     <depends optional-attribute-name="ConnectionManager">jboss.jca:service=DataSourceBinding,name=MySqlDS</depends>
                     <attribute name="SqlProperties">
    4. Instalar MySQL Java Connector, bajar el driver de MySQL y copiarlo al directorio lib del servidor.


 

 

Como un paso adicional creamos otro datasource para la base ejemplo del proyecto, creamos el archivo is346-ds.xml y lo ponemos tambien en el directorio deploy.

   1:<?xml version="1.0" encoding="UTF-8"?>
   2:
   3:<!-- $Id: mysql-ds.xml,v 1.3.2.1 2004/12/01 11:46:00 schrouf Exp $ -->
   4:<!--  Datasource config for MySQL using 3.0.9 available from:
   5:http://www.mysql.com/downloads/api-jdbc-stable.html
   6:-->
   7:
   8:<datasources>
   9:  <local-tx-datasource>
  10:    <jndi-name>IS346DS</jndi-name>
  11:    <connection-url>jdbc:mysql://localhost:9097/is346</connection-url>
  12:    <driver-class>com.mysql.jdbc.Driver</driver-class>
  13:    <user-name>root</user-name>
  14:    <password>lolo</password>
  15:    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
  16:    <!-- sql to call when connection is created
  17:    <new-connection-sql>some arbitrary sql</new-connection-sql>
  18:      -->
  19:    <!-- sql to call on an existing pooled connection when it is obtained from pool 
  20:    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
  21:      -->
  22:
  23:    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
  24:    <metadata>
  25:       <type-mapping>mySQL</type-mapping>
  26:    </metadata>
  27:  </local-tx-datasource>
  28:</datasources>
  29:

 

Antes de arrancar el jboss es importante levantar siempre primero el dbms, y en este caso crear las bases por ser la primera vez.

digital@localhost:~/mysql> ./mysql.server start
       digital@localhost:~/mysql> bin/mysql -u root -p mysql
       Enter password:
       Reading table information for completion of table and column names
       You can turn off this feature to get a quicker startup with -A       
Welcome to the MySQL monitor. Commands end with ; or \g.
         Your MySQL connection id is 1 to server version: 4.1.9-max-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> create database jbossdb;
         Query OK, 1 row affected (0.03 sec)

mysql> create database is346;
         Query OK, 1 row affected (0.03 sec)
 

Ahora si, podemos levantar el contenedor.

digital@localhost:~/jboss/bin> ./run.sh
=========================================================================
 JBoss Bootstrap Environment
 JBOSS_HOME: /home/digital/jboss
 JAVA: /opt/java/j2sdk/bin/java
 JAVA_OPTS: -server -Xms128m -Xmx128m -Dprogram.name=run.sh
 CLASSPATH: /home/digital/jboss/bin/run.jar:/opt/java/j2sdk/lib/tools.jar
=========================================================================
11:36:16,161 INFO [Server] Starting JBoss (MX MicroKernel)...
         11:36:16,163 INFO [Server] Release ID: JBoss [Zion] 4.0.1sp1 (build: CVSTag=JBoss_4_0_1_SP1          date=200502160314)
         11:36:16,164 INFO [Server] Home Dir: /home/digital/jboss
         11:36:16,165 INFO [Server] Home URL: file:/home/digital/jboss/
         11:36:16,165 INFO [Server] Library URL: file:/home/digital/jboss/lib/
         11:36:16,167 INFO [Server] Patch URL: null
         11:36:16,168 INFO [Server] Server Name: default
         11:36:16,168 INFO [Server] Server Home Dir: /home/digital/jboss/server/default
         11:36:16,169 INFO [Server] Server Home URL: file:/home/digital/jboss/server/default/
         11:36:16,170 INFO [Server] Server Data Dir: /home/digital/jboss/server/default/data
         11:36:16,171 INFO [Server] Server Temp Dir: /home/digital/jboss/server/default/tmp
         11:36:16,171 INFO [Server] Server Config URL: file:/home/digital/jboss/server/default/conf/
         11:36:16,172 INFO [Server] Server Library URL: file:/home/digital/jboss/server/default/lib/
         11:36:16,172 INFO [Server] Root Deployment Filename: jboss-service.xml
         11:36:16,178 INFO [Server] Starting General Purpose Architecture (GPA)...
         11:36:17,286 INFO [ServerInfo] Java version: 1.4.2_07,Sun Microsystems          Inc.
         11:36:17,286 INFO [ServerInfo] Java VM: Java HotSpot(TM) Server VM 1.4.2_07-b05,Sun          Microsystems Inc.
         11:36:17,287 INFO [ServerInfo] OS-System: Linux 2.6.8-24.11-default,i386
         11:36:18,431 INFO [Server] Core system initialized
         11:36:24,833 INFO [Log4jService$URLWatchTimerTask] Configuring from URL:          resource:log4j.xml
         11:36:25,177 INFO [WebService] Using RMI server codebase: http://localhost:8083/
         11:36:25,727 INFO [NamingService] Started jndi bootstrap jnpPort=1099,          rmiPort=1098, backlog=50, bindAddress=/0.0.0.0, Client SocketFactory=null,          Server SocketFactory=org.jboss.net.sockets.DefaultSocketFactory@ad093076
         11:36:40,597 INFO [Embedded] Catalina naming disabled
         11:36:43,591 INFO [Http11Protocol] Initializing Coyote HTTP/1.1 on http-0.0.0.0-8080
         11:36:43,794 INFO [Catalina] Initialization processed in 2749 ms
         11:36:43,795 INFO [StandardService] Starting service jboss.web
         11:36:43,802 INFO [StandardEngine] Starting Servlet Engine: Apache Tomcat/5.0.28
         11:36:43,943 INFO [StandardHost] XML validation disabled
         11:36:43,999 INFO [Catalina] Server startup in 204 ms
         11:36:44,623 INFO [TomcatDeployer] deploy, ctxPath=/invoker, warUrl=file:/home/digital/jboss/server/default/deploy/http-invoker.sar/invoker.war/
         11:36:47,823 INFO [TomcatDeployer] deploy, ctxPath=/ws4ee, warUrl=file:/home/digital/jboss/server/default/tmp/deploy/tmp16173jboss-ws4ee.war/
         11:36:48,471 INFO [TomcatDeployer] deploy, ctxPath=/, warUrl=file:/home/digital/jboss/server/default/deploy/jbossweb-tomcat50.sar/ROOT.war/
         11:36:49,310 INFO [TomcatDeployer] deploy, ctxPath=/jbossmq-httpil, warUrl=file:/home/digital/jboss/server/default/deploy/jms/jbossmq-httpil.sar/jbossmq-httpil.war/
         11:36:58,781 INFO [MailService] Mail Service bound to java:/Mail
         11:37:01,354 INFO [RARDeployment] Required license terms exist view the          META-INF/ra.xml: file:/home/digital/jboss/server/default/deploy/jboss-local-jdbc.rar
         11:37:02,078 INFO [RARDeployment] Required license terms exist view the          META-INF/ra.xml: file:/home/digital/jboss/server/default/deploy/jboss-xa-jdbc.rar
         11:37:02,750 INFO [RARDeployment] Required license terms exist view the          META-INF/ra.xml: file:/home/digital/jboss/server/default/deploy/jms/jms-ra.rar
         11:37:03,461 INFO [RARDeployment] Required license terms exist view the          META-INF/ra.xml: file:/home/digital/jboss/server/default/deploy/mail-ra.rar
         11:37:05,175 INFO [WrapperDataSourceService] Bound connection factory          for resource adapter for ConnectionManager 'jboss.jca:name=IS346DS,service=DataSourceBinding          to JNDI name 'java:IS346DS'
         11:37:06,642 INFO [ConnectionFactoryBindingService] Bound connection factory          for resource adapter for ConnectionManager 'jboss.jca:name=JmsXA,service=ConnectionFactoryBinding          to JNDI name 'java:JmsXA'
         11:37:07,336 INFO [WrapperDataSourceService] Bound connection factory          for resource adapter for ConnectionManager 'jboss.jca:name=MySqlDS,service=DataSourceBinding          to JNDI name 'java:MySqlDS'
         11:37:10,718 INFO [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=file:/home/digital/jboss/server/default/deploy/jmx-console.war/
         11:37:11,581 INFO [TomcatDeployer] deploy, ctxPath=/web-console, warUrl=file:/home/digital/jboss/server/default/deploy/management/web-console.war/
         11:37:14,320 ERROR [URLDeploymentScanner] Incomplete Deployment listing:
         MBeans waiting for other MBeans:
         ObjectName: jboss.mq:service=InvocationLayer,type=HTTP
         state: CONFIGURED
         I Depend On: jboss.mq:service=Invoker
         jboss.web:service=WebServer
 Depends On Me:
         ObjectName: jboss:service=KeyGeneratorFactory,type=HiLo
         state: CONFIGURED
         I Depend On: jboss:service=TransactionManager
         jboss.jca:name=DefaultDS,service=DataSourceBinding
 Depends On Me:
         ObjectName: jboss.mq:service=StateManager
         state: CONFIGURED
         I Depend On: jboss.jca:name=DefaultDS,service=DataSourceBinding
 Depends On Me: jboss.mq:service=DestinationManager
ObjectName: jboss.mq.destination:name=testTopic,service=Topic
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
         jboss.mq:service=SecurityManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=securedTopic,service=Topic
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
         jboss.mq:service=SecurityManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=testDurableTopic,service=Topic
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
         jboss.mq:service=SecurityManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=testQueue,service=Queue
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
         jboss.mq:service=SecurityManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=A,service=Queue
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=B,service=Queue
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=C,service=Queue
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=D,service=Queue
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
 Depends On Me:
         ObjectName: jboss.mq.destination:name=ex,service=Queue
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
 Depends On Me:
         ObjectName: jboss.mq:service=Invoker
         state: CONFIGURED
         I Depend On: jboss.mq:service=TracingInterceptor
 Depends On Me: jboss.mq:service=InvocationLayer,type=HTTP
         jboss.mq:service=InvocationLayer,type=JVM
         jboss.mq:service=InvocationLayer,type=UIL2
ObjectName: jboss.mq:service=TracingInterceptor
         state: CONFIGURED
         I Depend On: jboss.mq:service=SecurityManager
 Depends On Me: jboss.mq:service=Invoker
ObjectName: jboss.mq:service=SecurityManager
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
 Depends On Me: jboss.mq.destination:name=testTopic,service=Topic
         jboss.mq.destination:name=securedTopic,service=Topic
         jboss.mq.destination:name=testDurableTopic,service=Topic
         jboss.mq.destination:name=testQueue,service=Queue
         jboss.mq:service=TracingInterceptor
         jboss.mq.destination:name=DLQ,service=Queue
ObjectName: jboss.mq.destination:name=DLQ,service=Queue
         state: CONFIGURED
         I Depend On: jboss.mq:service=DestinationManager
         jboss.mq:service=SecurityManager
 Depends On Me:
         ObjectName: jboss.mq:service=InvocationLayer,type=JVM
         state: CONFIGURED
         I Depend On: jboss.mq:service=Invoker
 Depends On Me:
         ObjectName: jboss.mq:service=DestinationManager
         state: CONFIGURED
         I Depend On: jboss.mq:service=MessageCache
         jboss.mq:service=PersistenceManager
         jboss.mq:service=StateManager
 Depends On Me: jboss.mq.destination:name=testTopic,service=Topic
         jboss.mq.destination:name=securedTopic,service=Topic
         jboss.mq.destination:name=testDurableTopic,service=Topic
         jboss.mq.destination:name=testQueue,service=Queue
         jboss.mq.destination:name=A,service=Queue
         jboss.mq.destination:name=B,service=Queue
         jboss.mq.destination:name=C,service=Queue
         jboss.mq.destination:name=D,service=Queue
         jboss.mq.destination:name=ex,service=Queue
         jboss.mq:service=SecurityManager
         jboss.mq.destination:name=DLQ,service=Queue
ObjectName: jboss.mq:service=InvocationLayer,type=UIL2
         state: CONFIGURED
         I Depend On: jboss.mq:service=Invoker
 Depends On Me:
MBEANS THAT ARE THE ROOT CAUSE OF THE PROBLEM:
         ObjectName: jboss.jca:name=DefaultDS,service=DataSourceBinding
         state: NOTYETINSTALLED
         I Depend On:
         Depends On Me: jboss:service=KeyGeneratorFactory,type=HiLo
         jboss.mq:service=StateManager

         11:37:14,908 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-0.0.0.0-8080
         11:37:15,243 INFO [ChannelSocket] JK2: ajp13 listening on /0.0.0.0:8009
         11:37:15,253 INFO [JkMain] Jk running ID=0 time=0/108 config=null
         11:37:15,319 INFO [Server] JBoss (MX MicroKernel) [4.0.1sp1 (build: CVSTag=JBoss_4_0_1_SP1          date=200502160314)] Started in58s:610ms
       
 

Tablas creadas por JBoss para su propio funcionamiento

mysql> use jbossdb;
Database changed
mysql> show tables;
+-------------------+
| Tables_in_jbossdb |
+-------------------+
| JMS_MESSAGES |
| JMS_TRANSACTIONS |
| TIMERS |
+-------------------+
3 rows in set (0.00 sec)

mysql>

 

Ahora a desarrollar con JBuilder

11:40:40,286 INFO [EjbModule] Deploying Track
11:40:40,306 INFO [EjbModule] Deploying Artist
11:40:42,424 INFO [EJBDeployer] Deployed: file:/home/digital/jboss/server/default/deploy/EJBModule_Ejemplo.jar

 

mysql>
             mysql> show tables;
             +----------------------------------+
             | Tables_in_is346 |
             +----------------------------------+
             | Artist |
             | Track |
             | Track_artist_Artist_Track_artist |
             +----------------------------------+
             3 rows in set (0.00 sec)             
mysql> desc Artist;
               +-------+--------------+------+-----+---------+-------+
               | Field | Type | Null | Key | Default | Extra |
               +-------+--------------+------+-----+---------+-------+
               | id | int(11) | | PRI | 0 | |
               | name | varchar(250) | YES | | NULL | |
               +-------+--------------+------+-----+---------+-------+
               2 rows in set (0.08 sec)
mysql> desc Track;
               +----------+--------------+------+-----+---------+-------+
               | Field | Type | Null | Key | Default | Extra |
               +----------+--------------+------+-----+---------+-------+
               | id | int(11) | | PRI | 0 | |
               | title | varchar(250) | YES | | NULL | |
               | duration | int(11) | YES | | NULL | |
               +----------+--------------+------+-----+---------+-------+
               3 rows in set (0.01 sec)
mysql> desc Track_artist_Artist_Track_artist;
               +--------+---------+------+-----+---------+-------+
               | Field | Type | Null | Key | Default | Extra |
               +--------+---------+------+-----+---------+-------+
               | Track | int(11) | | PRI | 0 | |
               | Artist | int(11) | | PRI | 0 | |
               +--------+---------+------+-----+---------+-------+
               2 rows in set (0.00 sec)
11:45:58,752 INFO [EJBDeployer] Undeploying: file:/home/digital/jboss/server/default/deploy/EJBModule_Ejemplo.jar
11:45:58,851 INFO [EjbModule] Undeployed Artist
11:45:58,856 INFO [EjbModule] Undeployed Track
11:45:59,345 INFO [EjbModule] Deploying Track
11:45:59,393 INFO [EjbModule] Deploying Artist
11:46:00,297 INFO [EJBDeployer] Deployed: file:/home/digital/jboss/server/default/deploy/EJBModule_Ejemplo.jar

 

mysql> show tables;
+----------------------------------+
| Tables_in_is346 |
+----------------------------------+
| Artist |
| Track |
| Track_Artist |
| Track_artist_Artist_Track_artist |
+----------------------------------+
4 rows in set (0.00 sec)
mysql> drop table Track_artist_Artist_Track_artist;
                Query OK, 0 rows affected (0.00 sec)
mysql> desc Track_Artist;
              
               +-----------+---------+------+-----+---------+-------+
               | Field | Type | Null | Key | Default | Extra |
               +-----------+---------+------+-----+---------+-------+
               | track_id | int(11) | | PRI | 0 | |
               | artist_id | int(11) | | PRI | 0 | |
               +-----------+---------+------+-----+---------+-------+
               2 rows in set (0.00 sec)

 

Archivos generados

Archivos generados

mysql> select * from Track;
             +----+---------------+----------+
             | id | title | duration |
             +----+---------------+----------+
             | 4 | Rock and Roll | NULL |
             +----+---------------+----------+
             1 row in set (0.00 sec)             
mysql> select * from Artist;
               Empty set (0.00 sec)
mysql> select * from Track;
             +----+---------------+----------+
             | id | title | duration |
             +----+---------------+----------+
             | 12 | Rock and Roll | NULL |
             +----+---------------+----------+
             6 rows in set (0.00 sec)             
mysql> select * from Artist;
               +----+------+
               | id | name |
               +----+------+
               | 7 | U2 |
               | 8 | Aerosmith |
               +----+------+
               6 rows in set (0.00 sec)
mysql> select * from Track_Artist;
               +----------+-----------+
               | track_id | artist_id |
               +----------+-----------+
               | 12 | 7 | 
               | 12 | 8 |
               +----------+-----------+
               1 row in set (0.00 sec)
mysql> select * from Track;
             +----+---------------+----------+
             | id | title | duration |
             +----+---------------+----------+
             | 18 | Rock and Roll | NULL |
             +----+---------------+----------+
             1 row in set (0.00 sec)             
mysql> select * from Artist;
               +----+-----------+
               | id | name |
               +----+-----------+
               | 19 | U2 |
               | 20 | Aerosmith |
               +----+-----------+
               2 rows in set (0.00 sec)
mysql> select * from Track_Artist;
               +----------+-----------+
               | track_id | artist_id |
               +----------+-----------+
               | 18 | 19 |
               | 18 | 20 |
               +----------+-----------+
               2 rows in set (0.00 sec)
mysql> alter table Track_Artist rename Track_Artist2;
               Query OK, 0 rows affected (0.07 sec)

 

05:20:20,271 ERROR [LogInterceptor] TransactionRolledbackException              
in method: public abstract java.lang.Integer is346.TrackSessionFacade.createTrack(is346.TrackDto)              
throws javax.ejb.EJBException,java.rmi.RemoteException, causedBy:
org.jboss.tm.JBossRollbackException: Unable to commit, 
tx=TransactionImpl:XidImpl[FormatId=257,GlobalId=localhost/32, BranchQual=, localId=32] status=STATUS_NO_TRANSACTION;
- nested throwable: (javax.ejb.EJBException: Could insert relations into Track_Artist; CausedByException is:
Base table or view not found message from server: "Table 'is346.Track_Artist' doesn't exist")
at org.jboss.tm.TransactionImpl.commit(TransactionImpl.java:344)...

 

mysql> select * from Track;
               +----+---------------+----------+
               | id | title | duration |
               +----+---------------+----------+
               | 18 | Rock and Roll | NULL |
               +----+---------------+----------+
               1 row in set (0.00 sec)
mysql> select * from Artist;
               +----+-----------+
               | id | name |
               +----+-----------+
               | 19 | U2 |
               | 20 | Aerosmith |
               | 21 | U2 |
               | 22 | Aerosmith |
               +----+-----------+
               4 rows in set (0.00 sec)
mysql> select * from Track_Artist2;
               +----------+-----------+
               | track_id | artist_id |
               +----------+-----------+
               | 18 | 19 |
               | 18 | 20 |
               +----------+-----------+
               2 rows in set (0.00 sec)
mysql> alter table Track_Artist2 rename Track_Artist;
               Query OK, 0 rows affected (0.06 sec)
mysql> 
Agregando un finder nuevo

EJB QL Examples

SELECT DISTINCT OBJECT(p)
FROM Player p
WHERE p.position = ?1

Data retrieved: The players with the position specified by the finder method's parameter.

SELECT DISTINCT OBJECT(p)
FROM Player p
WHERE p.position = ?1 AND p.name = ?2

Data retrieved: The players with the specified position and name.

SELECT DISTINCT OBJECT(p)
FROM Player p
WHERE p.salary BETWEEN ?1 AND ?2

Data retrieved: The players whose salaries fall within the range of the specified salaries. ?

 

SELECT DISTINCT OBJECT(p)
FROM Player p, IN (p.teams) AS t
WHERE t.city = ?1

Data retrieved: The players whose teams belong to the specified city.

 

SELECT DISTINCT OBJECT(p)
FROM Player p, IN (p.teams) AS t
WHERE t.league.sport = ?1

Data retrieved: The players who participate in the specified sport.

 

Where Operators

...BETWEEN 8 AND 16

....Address.state IN ('FL','TX',?1)
NOT IN (similar al IN)

...IS NULL ....IS NOT NULL

...crs.reservations IS NOT EMPTY

..phone.number LIKE '222%'
Cuidado, no se pueden usar "input parameters" con LIKE, esto NO es válido
..phone.number LIKE '% ?1 %'

Functional Expressions

CONCAT(String1, String2)

LENGTH(String)

LOCATE(String1, String2 [,start])

SUBSTRING(String1, start, length)

ABS(number)

SQRT(double)

MOD(int,int)

Aggregate functions (select)

COUNT(identifier or path expression)

MAX(path expresssion), MIN (path expression)

AVG(numeric), SUM(numeric)

 

 

Proyecto en JBuilder .zip