JavaData & JavaDeveloping an Entity Bean and Session Bean Facade

Developing an Entity Bean and Session Bean Facade

In the previous article, we got started with developing an MVC application with JBoss Seam in JBoss Application Server 7. We created a JBoss Seam project and a JBoss Seam deployment structure. In this tutorial, we shall create an entity bean and a Session Bean façade as JBoss Seam components. Subsequently, JBoss Seam is integrated with EJB Session Beans.

This tutorial has the following sections:

  • Creating an Entity Bean JBoss Seam Component
  • Creating a Session Bean Façade JBoss Seam Component
  • Creating a JPA Configuration File
  • Integrating JBoss Seam with EJB Session Beans
  • Creating a JBoss Seam Component File

Creating an Entity Bean JBoss Seam Component

We shall use an EJB 3.0 entity bean for the domain model. In the next section on creating a session bean, we shall inject the entity bean as a Seam component into an annotated field. An entity bean is a POJO that represents a database table row. Annotate the entity class Catalog with the @Entity annotation and the @Table annotation. In the @Table annotation, specify the table name as catalogs. Also, annotate the entity class with the @NAME annotation, which specifies the component name of a Seam component. Specify scope with the @Scope annotation as SESSION, the default being CONVERSATION. The entity class implements the Serializable interface. Declare variables and getter/setter methods for bean properties id, journal, publisher, edition, title, and author. The @Id annotation specifies the identifier property. The @Column annotation specifies the column name associated with the property. The nullable element is set to false because the primary key is not nullable. Specify the generation strategy with the @GeneratedValue annotation. Because a MySQL database supports autoincrement of primary key column values by generating a sequence, set the generation strategy to GenerationType.AUTO. The Catalog.java entity class is listed below.

package org.jboss.seam.catalog;

import static org.jboss.seam.ScopeType.SESSION;
import java.io.Serializable;

import javax.persistence.*;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Entity
@Name("catalog")
@Scope(SESSION)
@Table(name="catalogs")
public class Catalog implements Serializable
{
   private static final long serialVersionUID =
      1881413500711441951L;

   private int id;
   private String journal;
   private String publisher;
   private String edition;
   private String title;
   private String author;

   public Catalog(){}
   public Catalog(String journal, String publisher,
      String edition, String title, String author)
   {
      this.journal = journal;
      this.publisher = publisher;
      this.edition = edition;
      this.title = title;
      this.author = author;
   }

   @Id
   @Column(name = "ID", nullable = false)
   @GeneratedValue(strategy = GenerationType.AUTO)
   public int getId() {
      return this.id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getJournal() {
      return this.journal;
   }

   public void setJournal(String journal) {
      this.journal = journal;
   }

   public String getPublisher() {
      return this.publisher;
   }

   public void setPublisher(String publisher) {
      this.publisher = publisher;
   }

   public String getEdition() {
      return this.edition;
   }

   public void setEdition(String edition) {
      this.edition = edition;
   }

   public String getTitle() {
      return this.title;
   }

   public void setTitle(String title) {
      this.title = title;
   }

   public String getAuthor() {
      return this.author;
   }

   public void setAuthor(String author) {
      this.author = author;
   }

}

The Catalog.java is shown in the Package Explorer.

Seam01
Figure 1: The Catalog.java file

Creating a Session Bean Façade JBoss Seam Component

In this section, we shall create a stateful session bean as a wrapper for the entity bean. The session bean has a method, create, to create an Catalog entity instance and a method, remove, to remove to remove a Catalog instance. Create a local interface CatalogSessionBean with just the method definitions for create and remove.

package org.jboss.seam.catalog;

import javax.ejb.Local;
@Local

public interface CatalogSessionBean
{
   public String create();

   public void remove();

}

Create a Stateful session CatalogBean that implements the local interface. Annotate the session bean with @Stateful to make the session bean stateful. Add the @Scope annotation to set the scope to ScopeType.CONVERSATION, which is also the default scope for a stateful session bean in Seam. Annotate the session bean class with @Name to make the session bean a Seam component and specify the component name in the name element.

@Stateful
@Scope(ScopeType.CONVERSATION)
@Name("catalogBean")
public class CatalogBean implements
   CatalogSessionBean
{

}

Inject the Seam component Catalog into a session bean field by using the @In annotation.

@In
private Catalog catalog;

Because Seam provides integration between the business logic layer and the presentation layer, the values are injected from the context variable into the attributes of the component instance annotated with @In. The catalog context variable values get injected into the attributes of the catalog component instance. The default name of the context variable is the same as the field annotated. Inject an EntityManager using the @PersistenceContext annotation.

@PersistenceContext
private EntityManager em;

Add a method remove() annotated with @Remove because Seam stateful session beans are required to include a method without parameters annotated with @Remove. Add a method, create, to create a Catalog instance. The create method shall be invoked from a JSF page. The Catalog entry values specified in the JSF page have value binding to the Seam component catalog. In the create() method, create a Query object using the createQuery(String) method of EntityManager. Run the SELECT query using the getResultList() method. If the query results List is empty, it indicates the Catalog instance is not already created. Persist the Catalog instance with the persist(Object) method. Return /createdCatalog.xhtml from the create() method to display a message in the browser. The stateful session bean class CatalogBean is listed below.

package org.jboss.seam.catalog;
import java.util.List;


import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.ScopeType;
import javax.ejb.Remove;


@Stateful
@Scope(ScopeType.CONVERSATION)
@Name("catalogBean")
public class CatalogBean implements CatalogSessionBean
{

   @In
   private Catalog catalog;

   @PersistenceContext
   private EntityManager em;



   public String create()
   {
      List catalogList = em.createQuery("select c.title from
         Catalog c where c.title=#{catalog.title}").getResultList();

      if

         (catalogList.size()==0)
         {
            em.persist(catalog);


         return "/createdCatalog.xhtml";
      }
      else
      {
         return null;
      }
   }
   @Remove
   public void remove() {}
}

The session bean classCatalogBean is shown in the Package Explorer.

Seam02
Figure 2: The session bean class CatalogBean

Creating a JPA Configuration File

Create a META-INF/persistence.xml configuration file in the catalog-ejb subproject. Specify the persistence provider as the Hibernate persistence provider org.hibernate.ejb.HibernatePersistence to be used for Object/Relational mapping of the entities to the database. Specify the persistence unit name as userDatabase and transaction-type as JTA (also the default). Specify the JTA datasource JNDI as java:jboss/datasources/MySQLDS. Specify the entity class for O/R mapping as org.jboss.seam.catalog.Catalog. Set the DDL generation strategy to create-drop with which the required tables are created and dropped. Set the hibernate.dialect to org.hibernate.dialect.MySQLDialect for a MySQL database. The persistence.xml configuration file is listed below.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
   
   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_2_0.xsd">
   <persistence-unit name="userDatabase" transaction-type="JTA">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <!-- If you are running in a production environment, add a managed
           data source, the example data source is just for development
           and testing! -->
      <jta-data-source>java:jboss/datasources/MySQLDS</jta-data-source>
      <class>org.jboss.seam.catalog.Catalog</class>
         <properties>
            <!-- Properties for Hibernate -->
            <property name="hibernate.hbm2ddl.auto" value="create-drop" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.dialect"
                      value="org.hibernate.dialect.MySQLDialect" />
         </properties>
   </persistence-unit>
</persistence>

The persistence.xml file is shown in the Package Explorer.

Seam03
Figure 3: The persistence.xml file

Integrating JBoss Seam with EJB Session Beans

In this section, we shall integrate Seam with the EJB container. EJB 3.0 session bean components may be integrated with Seam by using the interceptor class org.jboss.seam.ejb.SeamInterceptor. In the catalogcatalog-ejbsrcmainresourcesMETA-INFejb-jar.xml, configure the interceptor class and add a <assembly-descriptor/> element with interceptor binding to EJB name pattern *. Setting EJB name as * makes the SeamInterceptor as the default interceptor, which implies that all calls to all beans are within the deployment. The ejb-jar.xml is listed below.

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar 
         xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi_schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
         version="3.0">
   <interceptors>
      <interceptor>
         <interceptor-class>
            org.jboss.seam.ejb.SeamInterceptor
         </interceptor-class>
      </interceptor>
   </interceptors>
   <assembly-descriptor>
      <interceptor-binding>
         <ejb-name>*</ejb-name>
         <interceptor-class>
            org.jboss.seam.ejb.SeamInterceptor
         </interceptor-class>
      </interceptor-binding>
   </assembly-descriptor>
</ejb-jar>

Creating a JBoss Seam Component File

Seam components may be configured either using property settings in WEB-INF/web.xml or catalogcatalog-ejbsrcmainresourcesseam.properties, or the components.xml file. We shall use a components.xml file, which may be added to the WEB-INF folder of a WAR, the META-INF directory of a JAR or a JAR directory containing classes annotated with @Name. Add an empty seam.properties to the catalogcatalog-ejbsrcmainresources directory. Seam components catalog and catalogBean get installed when the deployment scanner finds @Name annotated classes in an archive with the seam.properties file. For Seam to find session beans in JNDI, specify the org.jboss.seam.core.init.jndiPattern property in the WEB-INF/components.xml file.

First, we need to create a components.xml file. Select File|New. In New, select Seam|Seam Component File and click Next.

Seam04
Figure 4: Creating a components.xml file

The New Seam Components gets started. Select the catalog/catalog-web/src/main/webapp/WEB-INF folder and specify Name as components.xml. Select Version as 2.3 and click Finish.

Seam05
Figure 5: Starting New Seam Components

The components.xml file gets added to the webapp/WEB-INF directory.

Seam06
Figure 6: Adding the components.xml file

Right-click components.xml in the Seam Components 2.3 Editor and select New|Component.

Seam07
Figure 7: Selecting a New Component

In the Add Component wizard, specify Name as org.jboss.seam.core.init and click Finish.

Seam08
Figure 8: Specifying the Name

The org.jboss.seam.core.init component gets added to components.xml. Next, add the jndiPattern property. Right-click org.jboss.seam.core.init and select Add Simple Property.

Seam09
Figure 9: Adding a Simple Property

In Add Simple Property, specify Name as jndiPattern and Value as java:app/catalog-ejb/CatalogBean. Click Finish.

Seam10
Figure 10: Specifying a Name

The org.jboss.seam.core.init.jndiName property gets added to components.xml, which is listed below.

Seam11
Figure 11: Adding the org.jboss.seam.core.init.jndiName property

<?xml version="1.0" encoding="UTF-8"?>

<components 
            xmlns_core="http://jboss.com/products/seam/core"
            xmlns_security="http://jboss.com/products/seam/security"
            xmlns_transaction="http://jboss.com/products/seam/transaction"
            xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi_schemaLocation=
               "http://jboss.com/products/seam/core
                http://jboss.com/products/seam/core-2.3.xsd
                http://jboss.com/products/seam/transaction
                http://jboss.com/products/seam/transaction-2.3.xsd
                http://jboss.com/products/seam/security
                http://jboss.com/products/seam/security-2.3.xsd
                http://jboss.com/products/seam/components
                http://jboss.com/products/seam/components-2.3.xsd">
   <component name="org.jboss.seam.core.init">
      <property name="jndiPattern">java:app/catalog-ejb/CatalogBean</property>
   </component>
</components>

The components.xml is shown in the Package Explorer.

Seam12
Figure 12: The components.xml file

In the next article, we shall add a Web descriptor for packaging & deploying the application, add a JSF user interface, and deploy and run the MVC application.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories