Sie sind auf Seite 1von 7

AT 70.

18: Software Architecture Design Asian Institute of Technology Handout 4: EJB Tutorial

January 2007 Computer Science and Information Management Instructor: Matthew Dailey

EJB Tutorial
This document is a brief tutorial on how to get started using EJB 3.0 with the JBoss application server and Eclipse. It shows how to deploy a JPA entity bean and a stateless session bean, as well as how to access the session bean from a remote client. The material in this tutorial came from a few dierent sources: Sebastian Hennebrueders First EJB 3 Tutorial explaining Ant and showing how to create session and entity beans with annotations and JBoss, available at http://www.laliluna.de/ejb-3-ant-tutorial-jboss.html. Eric Garridos Eclipse + JBossAS + EJB 3.0 setup instructions, available at http://www.ericgar.com/2006/10/17/eclipse-jbossas-ejb-30-setup-instructions. JBosss JBoss Eclipse IDE 1.5.0 Tutorial Guide, available at http://docs.jboss.com/jbosside/tutorial/build/en/html/index.html (the tutorial is out of date but contains some useful information). Bill Burke and Richard Monson-Haefels JBoss Workbook companion to Enterprise Java Beans 3.0 from OReilly. The source code for the workbook is available from http://www.oreilly.com/catalog/entjbeans5/index.html. I had to write a few les manually: the ant build specication le build.xml, the log conguration le log4j.properties, and the Java Persistence manager conguration le persistence.xml. If anyone with some JBoss Eclipse IDE experience knows how to simplify the creation of these les, please let me know. JDK installation: First you need Suns Java Development Kit version 1.5. On Ubuntu, use Synaptic to select packages sun-java5-jdk and sun-java5-plugin. JBoss installation: Next we install the JBoss Application Server. 1. Go to http://labs.jboss.com/portal and follow the Download link for JBoss AS. On the download page, select Run Installer for version 4.0.5. Firefox should automatically nd Sun Java 5.0 Web Start if you installed the Java 5 plugin previously. 2. Run the installer, accept the licensing terms. 3. Choose to install in your home directory for your personal testing purposes. 4. Choose the ejb3-clustered conguration. 5. Accept the defaults for the rest of the install. Verify that you can start your server by going to /jboss-4.0.5.GA/bin and running run.sh (probably run.bat for Windows). Eclipse installation: Next get Eclipse installed and running. On Ubuntu, use Synatic to select package eclipse. JBoss Eclipse IDE: This is optional. Its a little bit involved to do the installation of the IDE, but it will allow us to manage our JBoss server from inside Eclipse, and it provides a wizard for creating new EJB 3.0 projects that automatically adds the necessary JBoss/EJB3 class libraries. If you run into trouble, try Eric Garridos site (listed above), as it provides more detail on the procedure.

1. LOG IN AS ROOT, since you will be modifying the Eclipse installation. If youre running Windows and installed Eclipse yourself, you probably dont need any special administrative privileges. 2. Start Eclipse (eclipse from the command line), go to Help Software Updates select Search for new features to install. 3. If your Eclipse installation is not up to date, you can select Eclipse Project Updates then Eclipse 3.2.2, accept the license, and let the update manager update you to the latest version. 4. Next install the Eclipse Modeling Framework. Currently EMF 2.2.0 is required for the beta version of the JBoss Eclipse IDE. To do the install, after going to Search for new features to install, select Create a New Remote Site called Eclipse EMF with URL http://www.eclipse.org/emf/updates/, turn o Show latest version only, and install version 2.2.0. 5. Now you should be ready to install the development beta of the JBoss Eclipse IDE. Create a new remote site with name such as JBoss Eclipse IDE Plugins and URL http://download.jboss.org/jbosside/updates/development. 6. That should be everything you need. Go back to your normal user account and start up the newly updated Eclipse. Use the JBoss EJB3 wizard to start your project: 1. In Eclipse, go to File New Project, and under EJB 3.0, select EJB 3.0 Project. 2. Give the project a name. In this tutorial were building an application to help a humanitarian society keep track of stray dogs in Bangkok. Call your project dogwatch. 3. Next you need to associate the project with a JBoss server. Choose Create a JBoss Server, select the JBoss Inc. JBoss AS 4.0 (be sure to use JBoss Inc., not the other choices). Give the JBoss server a runtime name like default and point the Home Directory to the directory where you installed JBoss (/jboss-4.0.5.GA on Ubuntu). On the next screen, give the server a name (this one will appear in your server list in Eclipse) and click Finish. Create an entity bean: Recall that EJB 3.0 entity beans are just POJOs with some special deployment instructions. Here well create a Dog class and mark it as an entity with the necessary persistence mapping information. 1. Right click on src/ and select New Class. Give the new class the name Dog and put it in package edu.ait.dogwatch.entities. 2. Create the basic elds for your dog class: package edu.ait.dogwatch.entities; import java.io.Serializable; @Entity public class Dog implements Serializable { private static final long serialVersionUID = 1L; private int id; private int rfid; private String name; private String description; } 3. Add the getters and setters for your elds by right clicking on them and selecting Source Generate getters and setters.

4. Annotate the id eld as the primary key for the object-relational mapping, and ask the persistence manager to generate it for us automatically: @Id @GeneratedValue public int getId( ... 5. Add a nice toString() method so we can easily print out a dog: public String toString() { return "Dog " + getName() + ": " + getDescription(); } 6. Create the conguration le for the persistence manager for our application. Under src/ add a Folder named META-INF/, and create a le persistence.xml in that folder with contents: <persistence> <persistence-unit name="dogwatch"> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> <!-- Use value="create-drop" if you want the DB recreated each time the entity bean is deployed, or value="update" to save the DB over redeploys and server reboots. --> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence> The specication denes our persistence unit as dogwatch. The jta-data-source is java:/DefaultDS indicating well use the Hypersonic SQL database embedded into JBoss. Weve also specied that the persistence manager will automatically update the relational schema as needed when the objectrelational-mapping changes, but not to drop tables when our application is undeployed. Create a session bean: The JBoss Eclipse IDE provides a wizard for creating session beans. A remote interface will automatically be created for each bean. If you also want a local interface, youll have to add it yourself. 1. Right click on your project and select New Other EJB 3.0 Session Bean. Use edu.ait.dogwatch.dogmanager for the package name and DogManager for the bean name. Lets keep it stateless. 2. Add three methods to the remote interface, called DogManager: public Dog findDog( int pKey ); public List findDog( String name ); public void createDog( Dog dog ); 3. In the bean class (DogManagerBean) ask the container to inject a reference to the EntityManager: public @Stateless class DogManagerBean ... @PersistenceContext( unitName="dogwatch" ) private EntityManager manager; 4. Lets be specic about the beans remote JNDI name:

public @Stateless class DogManagerBean ... public static final String RemoteJNDIName = DogManagerBean.class.getSimpleName() + "/remote"; 5. Creating a new entity involves asking the EntityManager to make the object persistent: public void createDog( Dog dog ) { manager.persist( dog ); } 6. Finding an entity by primary key involves asking the EntityManager to find() it: public Dog findDog( int pKey ) { return manager.find( Dog.class, pKey ); } 7. To nd entities by other means requires EJB QL queries: import java.util.List; ... public List findDog( String name ) { Query query = manager.createQuery( "from Dog d where d.name = ?1" ); query.setParameter( 1, name ); return query.getResultList(); } Create the ant build le: Eclipse integrates nicely with ant, which automates the process of building, deploying, and running application code. Here well create a simple build le for our application, step by step: 1. Add a le named build.xml under the dogwatch project. 2. Add the following text to your le: <?xml version="1.0" encoding="ISO-8859-1"?> <project name="dogwatch" basedir="." default="deploy"> <property name="classes.dir" value="classes" /> <property name="jboss.home" value="/home/mdailey/jboss-4.0.5.GA" /> <property name="deploy.dir" value="${jboss.home}/server/default/deploy" /> <property name="src.dir" value="src" /> </project> This gives the project a name and names the default target (deploy, which well dene in a moment). Then we list the set of properties that will be used in the rest of the build le. Properties are arbitrary names which can be expanded to their values with the syntax $propname. Replace /home/mdailey with the appropriate directory for your JBoss installation. 3. Next lets dene the CLASSPATH to be used when compiling source code and executing client code: <path id="base.path"> <fileset dir="${jboss.home}/server/default/lib"> <include name="*.jar" /> </fileset> <fileset dir="${jboss.home}/server/default/deploy/ejb3.deployer"> <include name="*.jar" />

</fileset> <fileset dir="${jboss.home}/server/default/deploy/jboss-aop-jdk50.deployer"> <include name="*.jar" /> </fileset> <fileset dir="${jboss.home}/lib"> <include name="*.jar" /> </fileset> <pathelement location="${classes.dir}" /> <!-- So that Java can find jndi.properties and log4j.properties when executing Client --> <pathelement location="${basedir}/src" /> </path> 4. Lets add our rst target, to clean up any .class les created during compilation: <target name="clean" description="Delete all generated files"> <delete dir="${classes.dir}" /> </target> When we ask ant to execute this target, it will simply delete the classes/ directory and everything in it. 5. Now lets add a target to compile all of our .java les: <target name="compile" description="Compiles the Task"> <mkdir dir="${classes.dir}" /> <javac srcdir="${src.dir}" destdir="${classes.dir}"> <classpath> <path refid="base.path" /> </classpath> </javac> </target> This target makes the ${classes.dir} directory then compiles the .java les under ${src.dir} and puts the resulting .class les in ${classes.dir}. 6. Next we create a target to deploy our EJBs to the JBoss application server: <target name="deploy" description="JARs the Task" depends="compile"> <jar destfile="${deploy.dir}/${ant.project.name}.jar"> <metainf dir="${src.dir}/META-INF" /> <fileset dir="${classes.dir}"> <include name="edu/**/*.class" /> <exclude name="edu/ait/dogwatch/clients/**/*.class" /> </fileset> </jar> </target> This target, which depends on the compile target (meaning it should be executed rst), creates a JAR le named dogwatch.jar in the JBoss server/default/deploy/ directory, which will cause JBoss to load and set up the EJBs inside. The property ${ant.project.name} is a built in property set to the project name already dened in the <project> tag. The JAR le will include our class les except the edu.ait.dogwatch.clients classes, which shouldnt be deployed to the server. It will also contain the metadata in META-INF, in our case just persistence.xml. 7. Next lets add a target to undeploy our JAR le:

<target name="undeploy" description="Undeploy jar from server"> <delete file="${deploy.dir}/${ant.project.name}.jar" /> </target> JBoss will automatically undeploy the EJBs in the JAR when it notices the JAR le has been removed. 8. Finally, lets add a target to run the test client (which we havent created yet, but thats OK): <target name="run.client" depends="deploy"> <java classname="edu.ait.dogwatch.clients.Client" fork="yes" dir="."> <classpath refid="base.path"/> </java> </target> Here were asking Java to execute a client class Client using the CLASSPATH dened earlier. This obviously wont work until we create the client class, in a moment. Test the ant build le: Here well make sure the Ant conguration and the EJBs are properly congured. 1. In Eclipse, go to Window Show View Ant. You should get an Ant view. Drag your build.xml le from the package explorer to the Ant view, or right click in the window and Add Buildles to add it. You should see the dierent Ant targets listed. 2. Make sure your JBoss server is running, and test the clean, compile, deploy, and undeploy targets by double-clicking on them. 3. You can check that your DogManagerBean is deployed by pointing your Web browser to http://localhost:8080, selecting the JMX Console, selecting service=JNDIView, then under the heading java.lang.String list(), click on the Invoke button to output all the JNDI information for this server instance. Look for DogManagerBean under the Global JNDI Namespace heading. Create simple test client application: Finally, lets make a client to connect to our session bean through a proxy stub. 1. Add a new class in package edu.ait.dogwatch.clients. 2. Add the main() method: import java.util.Iterator; public class Client { public static void main( String [] args ) { try { Context jndiContext = new InitialContext(); String jndiName = DogManagerBean.RemoteJNDIName; DogManager beanRemote = (DogManager)jndiContext.lookup( jndiName ); // See if our dog Spotty already exists (by name) List dogList = beanRemote.findDog( "Spotty" ); if ( dogList.isEmpty() ) { Dog dog; System.out.println( "No Spotty dog yet -- creating..." ); dog = new Dog(); dog.setName( new String( "Spotty" )); dog.setDescription(

new String( "Medium-sized, brown with white spots" )); beanRemote.createDog( dog ); System.out.println( "Created " + dog.toString() ); } else { Iterator it = dogList.iterator(); System.out.println( "Found Spotty dogs already:" ); while( it.hasNext() ) { Dog dog = (Dog)it.next(); System.out.println( dog.toString() ); } } } catch ( javax.naming.NamingException ne ) { ne.printStackTrace(); } } } rst we use JNDI to get a reference to a proxy stub for our sesion bean. Then we ask the bean to return a list of all Dog objects with name "Spotty". If none exist yet, we ask the session bean to create one. 3. For this to work, JNDI has to know where to lookup naming information. This setup is provided in the le jndi.properties, which the EJB 3.0 wizard should have created for you when you created the project. Lets look at its contents: java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099 This is the standard way to tell JNDI to use the JBoss server on the local machine. Java nds our jndi.properties when we run Client because its in the CLASSPATH specied in our Ant run.client target. 4. Finally, we need to congure logging for the client. Add a le log4j.properties under src/ with these contents: # Send log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=debug, stdout This will allow us to see any log messages generated during execution on the console. 5. Now you should be ready to run the test client. Double-click on the target in the Ant view. Verify that the second time you execute, that good old Spotty is already persistent. 6. To view the Hypersonic SQL database, you can go back to the JMX console, select database=default,service=Hypersonic then press the Invoke button for the startDatabaseManager() MBean operation. This should give you a HSQL Database Manager window. You should be able to browse the schema for the DOG table and execute a query such as SELECT * FROM DOG. Whoohoo! Your rst EJB 3.0 application is up and running!

Das könnte Ihnen auch gefallen