EJB 3.0 web service example

ejb3 web service annotations example and ejb 2.0 tutorial for beginners with examples
JohenCorner Profile Pic
JohenCorner,France,Professional
Published Date:02-08-2017
Your Website URL(Optional)
Comment
Creating an EJB 3.0 Web Service JAX-WS is an API to create web applications and web services using the XML- based web services functionality. A web service consists of a Service Endpoint Implementation (SEI) class, which must satisfy the following points: • It's annotated with thejavax.jws.WebService annotation • It must not be abstract or final • It must contain a default public constructor • A web service provides operations, which are public methods, that are made available to web service clients The business methods must not bestatic orfinal and, though not required, may be annotated with thejavax.jws.WebMethod annotation. By default, allpublic methods are made available as web service operations. In this chapter, we shall create an EJB 3.0 web service with JDeveloper 11g, WebLogic Server 11g, and Oracle Database. We shall discuss the following topics in this chapter: • Creating a data source in WebLogic Server • Creating an entity bean • Creating a session bean façade • Creating a Web Service class • Creating a web service client • Testing the web service aCreating an EJB 3.0 Web Service Setting the environment We need to download and install JDeveloper 11g Studio edition and WebLogic Server 11g, both of which are components of Oracle Fusion Middleware 11g (http://www.oracle.com/technology/software/products/middleware/ index.html). We will also need to create a new WebLogic domain with the Fusion Middleware Configuration Wizard. As for the entity bean persistence, we need to download and install Oracle Database 10g XE (http://www.oracle.com/ technology/software/products/database/index.html). Create a user OE with the following SQL commands: CREATE USER OE IDENTIFIED BY pw; GRANT CREATE SESSION, DBA to OE; Create a test tableCATALOG in database schemaOE with the following SQL script: CREATE TABLE Catalog (id INTEGER PRIMARY KEY NOT NULL, journal VARCHAR(100), publisher VARCHAR(100), edition VARCHAR(100), title VARCHAR(100), author VARCHAR(100)); Creating a JDeveloper application First, we create an EJB 3.0 Application in JDeveloper. Here is how to do it: 1. Select New Application. 2. Specify an Application Name (EJB3WebService), select the Java EE Web Application template, which consists of a Model project and a ViewController project, and click on Next. 3. Next, specify the name (ViewController) for the View and Controller project. 4. In the Project Technologies tab, transfer the EJB project technology from the Available list to the Selected list using the button. 5. Click on Next. 6. Select the default Java settings for the View project and click on Next. 7. Configure the EJB Settings for the View project. 8. Select EJB Version as Enterprise JavaBeans 3.0 and select Using Annotations. 9. Click on Next. 10. Next, create the Model project. Specify the Project Name (EJB3Model, for example) and in the Project Technologies tab, transfer the EJB project technology from the Available list to the Selected list using the button. Click on Next. 384 aChapter 10 11. Select the default Java settings for the Model project and click on Next. 12. Configure the EJB settings for the Model project similar to the View project. Select EJB Version as Enterprise JavaBeans 3.0, select Using Annotations, and click on Finish. An EJB 3.0 application, which consists of a Model project and a ViewController project, gets added in the Application tab: Creating a database connection Next, we need to create a JDBC connection in JDeveloper with the Oracle database. Here is how we go about it: 1. Open the Database Navigator with View Database Database Navigator or select the Database Navigator tab if already open. 2. Right-click on the IDE Connections node and select New Connection. 3. In the Create Database Connection window, specify a Connection Name. 4. Select Connection Type as Oracle (JDBC). 5. Specify Username as OE, which is the schema in which the Catalog table is created. 6. Specify the password for the OE schema. 385 aCreating an EJB 3.0 Web Service 7. Select Driver as thin, Host Name as localhost, SID as ORCL, and JDBC Port as 1521. 8. Click on the Test Connection button to test the connection. 9. If the connection gets established, click on OK. 10. The OracleDBConnection gets added to the Database Navigator view. Creating a data source in the WebLogic server In order to create a data source in the WebLogic server, follow these steps: 1. Start the WebLogic server and navigate to the Administration Console with the URLhttp://localhost:7001/console. 2. Select the Services JDBC node and select the Data Sources section. 3. In the Data Sources table, click on New to create a new data source. 386 aChapter 10 4. Specify the data source Name and the JNDI Name (jdbc/ OracleDBConnectionDS) for the data source. 5. Select Database Type as Oracle and click on Next: 387 aCreating an EJB 3.0 Web Service 6. Select the default Database Driver, Oracle's Driver (Thin XA), and click on Next: 7. With the XA JDBC driver, the default transaction options are to support global transactions and the Two-Phase Commit global transaction protocol. Click on Next: 8. In the Connection Properties window, specify: ° Database Name as XE 388 aChapter 10 ° Host Name as localhost, Port as 1521 ° Database User Name as OE ° The Password 9. Click on Next: 10. Click on Test Configuration to test the database connection. If the connection gets established, click on Next: 389 aCreating an EJB 3.0 Web Service 11. Select the AdminServer as the target server to deploy the data source and click on Finish: 12. A data source gets added to the Data Sources table: 390 aChapter 10 Creating an entity bean Next, we create an EJB 3.0 entity bean from the Oracle database tableCATALOG that we created earlier. Here's how to go about it: 1. Select the EJB3Model project in the Application navigator and select File New. 2. In the New Gallery window, select Categories Business Tier EJB and Items Entities from Tables and click on OK. 3. In the Persistence Unit window, select New to create a new persistence unit. In the New Persistence Unit window, specify a persistence unit name (em). 4. Specify JTA DataSource Name as jdbc/OracleDBConnectionDS, which is the data source name corresponding to theOracleDBConnection connection. 5. Select the settings for Toplink; Database Platform as Oracle and Server Platform as WebLogic 10. Click on OK. 6. The em Persistence Unit gets created. Click on OK in the Persistence Unit window. 7. Select Type of Connection as Online Database Connection and click on Next. 8. In the Database Connection Details window, select the OracleDBConnection and click on Next. 9. In the Select Tables window, select Schema as OE, Name Filter as %, and check the Auto-Query checkbox. 391 aCreating an EJB 3.0 Web Service 10. Select the CATALOG table and click on Next: 11. Select the default settings in the General Options window. The default package name is model. 12. In the Entity Class, select Place member annotations on Fields, and select the Implement java.io.Serializable checkbox. Click on Next. 13. In the Specify Entity Details window, select Table Name as OE.CATALOG. Specify Entity Name as Catalog and Entity Class as model.Catalog. Click on Next. 14. In the Summary Page, click on Finish. The entity bean classmodel.Catalog gets created. Thepersistence.xml deployment descriptor gets created in theMETA-INF directory: 392 aChapter 10 The Entity class The entity bean class is just a POJO class annotated with theEntity annotation. A NamedQuery specifies a findAll query, which selects all the entity instances. An entity bean, which is persisted to a database, that has caching enabled, is serialized by caches. Therefore, the entity bean class implements thejava.io.Serializable interface. Specify aserialVersionUID variable, which is used by serialization runtime to associate a version number with the serializable class: private static final long serialVersionUID = 7422574264557894633L; The database columns are mapped to entity bean properties, which are defined as private variables. The getter setter methods for the properties are also den fi ed. The identifier property is specified with the Id annotation. TheColumn annotation specifies that the id column is notnullable: Id Column(nullable = false) private long id; 393 aCreating an EJB 3.0 Web Service By default, theid column of typeINTEGER is mapped to a field of type Long. Modify theid field to type long. The entity bean class is listed as follows: package model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; Entity NamedQueries( NamedQuery(name = "Catalog.findAll", query = "select o from Catalog o") ) public class Catalog implements Serializable private String author; private String edition; private static final long serialVersionUID = 7422574264557894633L; Id Column(nullable = false) private long id; private String journal; private String publisher; private String title; public Catalog() super(); public Catalog(String author, String edition, long id, String journal, String publisher, String title) super(); this.author = author; this.edition = edition; this.id = id; this.journal = journal; this.publisher = publisher; this.title = title; public String getAuthor() return author; public void setAuthor(String author) this.author = author; 394 aChapter 10 public String getEdition() return edition; public void setEdition(String edition) this.edition = edition; public long getId() return id; public void setId(long id) this.id = id; public String getJournal() return journal; public void setJournal(String journal) this.journal = journal; public String getPublisher() return publisher; public void setPublisher(String publisher) this.publisher = publisher; public String getTitle() return title; public void setTitle(String title) this.title = title; 395 aCreating an EJB 3.0 Web Service The entity Persistence Configuration file Thepersistence.xml file is used to define the persistence unit/s, which includes a JTA data source that is used for database persistence. The persistence provider is specified as org.eclipse.persistence.jpa.PersistenceProvider. Thejta- data-source is defined as java:/app/jdbc/jdbc/OracleDBConnectionDS. The eclipselink.target-server property is specied as fi WebLogic_10. Thejavax. persistence.jtaDataSource property is specied as fi java:/app/jdbc/jdbc/ OracleDBConnectionDS. Thejava:/app/jdbc prefix gets added to the JTA Data Source specified when creating the persistence unit. Remove the java:/app/jdbc prefix as we are using an external WebLogic server, not the integrated WebLogic server. Thepersistence.xml cong fi uration file is listed as follows: ?xml version="1.0" encoding="windows-1252" ? persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0" persistence-unit name="em" providerorg.eclipse.persistence.jpa.PersistenceProvider /provider jta-data-sourcejdbc/OracleDBConnectionDS/jta-data-source classmodel.Catalog/class properties property name="eclipselink.ddl-generation" value="none" / property name="eclipselink.target-server" value="WebLogic_10" / property name="javax.persistence.jtaDataSource" value="jdbc/OracleDBConnectionDS" / property name="eclipselink.target-database" value="Oracle10g" / /properties /persistence-unit /persistence Creating a stateless session bean As we already discussed, it's always a good practice to create a session bean façade for an entity bean. This is done to ensure that the entity bean is not directly accessed by a client. To create a session bean, follow the given steps: 1. Select the EJB3Model project and select File New. 2. In the New Gallery window, select Categories Business Tier EJB and Items Session EJB. Click on OK. 396 aChapter 10 3. Specify the EJB Name as CatalogSessionEJB. Select Session Type as Stateless and Transaction Type as Container. Specify a mapped name (EJB3-SessionEJB). The Generate Session Façade Methods checkbox is selected by default. The Entity Implementation is JPA Entities by default. The persistence unit is em. Click on Next. 4. Select the default JPA Entity Methods to create and click on Next. 5. Specify the Bean Class (model. CatalogSessionEJBBean) and click on Next. 6. Select the EJB business interface to implement. Select the Implement a Remote Interface checkbox, and specify the Remote interface (model. CatalogSessionEJB). Click on Next. 7. In the Summary window, click on Finish. A session bean classCatalogSessionEJBBean gets added to the entity bean model project. The remote business interface for the session bean,CatalogSessionEJB, also gets created. 397 aCreating an EJB 3.0 Web Service The session bean class TheCatalogSessionEJBBean class is annotated with the annotationStateless. ThemappedName attribute specifies the global JNDI for the session bean. We shall use the mapped name in the web service to look up the session bean and invoke method/s on it. TheRemote annotation indicates that the session bean is a remote interface: Stateless(name = "CatalogSessionEJB", mappedName = "EJB3-SessionEJB") Remote public class CatalogSessionEJBBean implements CatalogSessionEJBRemote Two types ofEntityManagers are supported by the JPA: application-managed EntityManager and container-managedEntityManager. Container-managedEntityManagers always use JTA transactions, which are managed by the EJB container and are created by injecting using the PersistenceContext annotation or by direct lookup of the entity manager in the JNDI namespace. Application-managed entity managers may use JTA or resource-local transactions. Application-managed entity managers are created by injecting an EntityManagedFactory with thePersistenceUnit annotation and subsequently invoking thecreateEntityManager() method on theEntityManagedFactory object. We are using a container-managed entity manager. In the session bean, inject an EntityManager using thePersistenceContext annotation. One of the value-added features of WebLogic Server 10.3 is that if the injected variable's name is the same as the persistence unit, theunitName attribute of thePersistenceContext or PersistenceUnit is not required to be specie fi d, though we have specie fi d it. The type attribute is set toPersistenceContextType.TRANSACTION, which implies that the persistence context is transaction-scoped. PersistenceContext(unitName = "em", type = PersistenceContextType.TRANSACTION) EntityManager em; Add a methodpersistEntity() and a methodtest() to the session bean and the remote interface. ThepersistEntity method is used to persist an entity using the persist() method. Subsequent to persisting an entity instance, invoke theflush() method to synchronize the entity manager with the database: em.persist(entity); em.flush(); 398 aChapter 10 In thetest() method, we shall create aCatalog entity instances and persist the entities to the database. We shall also query the entity instances. In thetest() method, set the flush mode to COMMIT, which implies that the changes to the entity manager are synchronized to the database when the transaction commits: em.setFlushMode(FlushModeType.COMMIT); Create aCatalog entity instance and persist it to the database. We need to merge the entity instance with the entity manager using themerge() method before persisting it. Catalog catalog1 =new Catalog("Kimberly Floss", "Nov-Dec 2004", new Integer(1), Oracle Magazine", "Oracle Publishing", "Database Resource Manager"); Catalog c1 = em.merge(catalog1); persistEntity(c1); Similarly, create and persist two more entity instances. An entity instance may be found with the Java persistence query language. For example, find a catalog entity instance by author name. First, create an instance of theQuery object using the createQuery method to run a Java persistence query language statement. Bind the author name to a named parametername using thesetParameter method of the Query object and run the Java persistence query statement using thegetResultList method, which returns aList: List catalogList =em.createQuery("SELECT c from Catalog c where c.author=:name").setParameter ("name","Jonas Jacobi"). getResultList(); Iterate over theList, which is actually just one catalog entry, to retrieve theCatalog entity instance. Create aString, which will be returned by thetest() method, from theCatalog instance properties: for (Iterator iter = catalogList.iterator(); iter.hasNext(); ) Catalog element = (Catalog)iter.next(); catalogEntry =catalogEntry + " Journal: " + element.getJournal() + "Publisher: " + element.getPublisher() + " Edition: " + element.getEdition() + " Title: " + element.getTitle() + " Author: " + element.getAuthor(); 399 aCreating an EJB 3.0 Web Service Similarly, all the titles may be listed and all theCatalog entity instances may be listed. An entity instance may be removed using theremove() method. To remove an entity instance, create the entity instance, merge the entity instance with the entity manager using themerge() method, and remove the entity instance using the remove() method: Catalog catalog2 =new Catalog("Jonas Jacobi", "Nov-Dec 2004", new Integer(2),"Oracle Magazine", "Oracle Publishing", "From ADF UIX to JSF"); Catalog c2 = em.merge(catalog2); em.remove(c2); em.flush(); Annotate thetest() method with theTransactionAttribute annotation with type set toREQUIRES_NEW, which implies that a new transaction is created for the test() method in the session bean: TransactionAttribute(TransactionAttributeType.REQUIRES_NEW The session bean class is listed as follows: package model; import java.util.Iterator; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.FlushModeType; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import javax.persistence.PersistenceUnit; import javax.persistence.Query; import javax.transaction.UserTransaction; Stateless(name = "CatalogSessionEJB", mappedName = "EJB3-SessionEJB") Remote public class CatalogSessionEJBBean implements CatalogSessionEJB PersistenceContext(unitName = "em", type = PersistenceContextType.TRANSACTION) EntityManager em; public CatalogSessionEJBBean() 400 aChapter 10 TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public String test() String catalogEntry = "A catalog entry: "; try em.clear(); em.setFlushMode(FlushModeType.COMMIT); Catalog catalog1 = new Catalog("Kimberly Floss", "Nov-Dec 2004", new Integer(1), "Oracle Magazine", "Oracle Publishing", "Database Resource Manager"); Catalog c1 = em.merge(catalog1); persistEntity(c1); Catalog catalog2 =new Catalog("Jonas Jacobi", "Nov-Dec 2004", new Integer(2),"Oracle Magazine", "Oracle Publishing", "From ADF UIX to JSF"); Catalog c2 = em.merge(catalog2); persistEntity(c2); Catalog catalog3 =new Catalog("Steve Muench", "March-April 2005", new Integer(3),"Oracle Magazine", "Oracle Publishing", "Starting with Oracle ADF"); Catalog c3 = em.merge(catalog3); persistEntity(c3); / catalog2 =new Catalog("Jonas Jacobi", "Nov-Dec 2004", new Integer(2),"Oracle Magazine", "Oracle Publishing","From ADF UIX to JSF"); c2 = em.merge(catalog2); em.remove(c2); em.flush(); catalog3 =new Catalog("Steve Muench", "March-April 2005", new Integer(3),"Oracle Magazine", "Oracle Publishing", "Starting with Oracle ADF"); c3 = em.merge(catalog3); em.remove(c3); em.flush();/ List catalogList = em.createQuery("SELECT c from Catalog c where c.author=:name").setParameter ("name","Jonas Jacobi").getResultList(); for (Iterator iter = catalogList.iterator(); iter.hasNext(); ) Catalog element = (Catalog)iter.next(); 401 aCreating an EJB 3.0 Web Service catalogEntry =catalogEntry + " Journal: " + element.getJournal() + " Publisher: " + element.getPublisher() + " Edition: " + element.getEdition() + " Title: " + element.getTitle() + " Author: " + element.getAuthor(); catalogEntry = catalogEntry + " All Titles: "; List allTitles =em.createQuery("SELECT c from Catalog c"). getResultList(); for (Iterator iter = allTitles.iterator(); iter.hasNext(); ) Catalog element = (Catalog)iter.next(); catalogEntry = catalogEntry + " Title: " + element.getTitle(); catalogEntry = catalogEntry + " All catalog entity instances: "; List allCatalogEntries = em.createQuery("SELECT c from Catalog c").getResultList(); for (Iterator iter = allCatalogEntries.iterator(); iter.hasNext(); ) Catalog element = (Catalog)iter.next(); catalogEntry = catalogEntry + " Catalog Entry: " + element; catch (Exception e) catalogEntry = e.getMessage(); em.clear(); return catalogEntry; public void persistEntity(Catalog entity) em.persist(entity); em.flush(); The corresponding remote interface is listed as follows: package model; import java.util.List; import javax.ejb.Remote; 402 a