<document>
  <header>
    <product>resin-ee</product>
    <resin-2.0>$ee/ejb-tut/cmp-basic.xtp</resin-2.0>
    <title>Basic CMP</title>
        <description>
          <p>Scenario: Headmaster Dumbledore needs a database of Courses.</p>
          <p>This example focuses on:</p>
          <ul>
            <li>Introduces Container Managed Persistance (CMP) fundamental concepts</li>
            <li>Setting up the database to work with Resin-CMP</li>
            <li>Developing the local-home, local, and EntityBean classes</li>
            <li>Writing the deployment descriptor (cmp-basic.ejb)</li>
            <li>Developing a Servlet to lookup and use the entity bean</li>
            <li>Configuring Resin to deploy the EJB and use JNDI</li>
          </ul>
        </description>
    <type>tutorial</type>
    <tutorial-startpage>basic</tutorial-startpage>
  </header>

  <body>
    <summary/>

<note>The <a href="ejb3|tutorial/cmp-basic/index.xtp">EJB 3.0 Basic</a>
tutorial describes the same example for EJB 3.0.
You can compare the two tutorials to help evaluate which
technology best suits your application.</note>

<p>Resin-CMP manages tables in a relational database using a Java
bean interface.  Each database table corresponds to a single "entity bean".  
(Since Resin-CMP uses the EJB specification, most of its jargon
comes from EJB.)  By creating an entity bean with container managed
persistence, you let Resin-CMP generate the SQL to load, store, and
cache entity beans from the database.  Avoiding SQL is an advantage in
itself, but the primary advantage is the increased flexiblity of your
application code.  Maintenance and code-refactoring can focus on the
beans instead of changing lots of SQL statements in the program.</p>

<p>In this example, Hogwarts School of Witchcraft and Wizardry uses
Resin-CMP to manage its list of courses offered for the term.  Each
course has a name and a teacher for the course.  The example has been
simplified as much as possible; following examples show how to
<a href="../cmp-find/index.xtp">query the database</a> and <a
href="../cmp-create/index.xtp">create and remove</a> database entries.</p>

<section title="Database Schema">

<p>The database table uses the course name as the primary key.  Each bean
in Resin-CMP needs its own primary key.  It is possible to let the
database generate primary keys, e.g. automatically generated integers.
Since this example only reads data from
the table, we'll prepopulate it with the courses.</p>

<p>Each table maps to a single object, using the
<code/abstract-schema-name/> and <code/sql-table/>
in the ejb.xml.  If you look at the
distribution's database schema (in cmp/WEB-INF/sql/default.sql),
you'll notice that each example has its own table, e.g. basic_courses
and find_courses, even though the examples often share the same
table.  Generally a Resin-CMP bean has complete control over a database
table.  Because it controls the table, the bean can cache data without
worrying that the database will change without its knowledge.</p>

<p>Database columns map to accessor methods in the bean, using standard
rules.  The <code/id/> field maps to <code/getId/>.
The <code/instructor/> column maps to <code/getInstructor/> and
<code/setInstructor/>.</p>

<example title="course.sql">
CREATE TABLE basic_courses (
  id VARCHAR(250) NOT NULL,
  teacher VARCHAR(250),

  PRIMARY KEY(id)
);

INSERT INTO basic_courses VALUES('Potions', 'Severus Snape');
INSERT INTO basic_courses VALUES('Transfiguration', 'Minerva McGonagall');
</example>

</section>

<section title="Implementation Classes">

<p>Each database table corresponds to a single "entity bean".  
Since Resin-CMP uses the EJB specification, most of its the jargon
comes from EJB.  The developer needs to write three classes for each
entity bean:</p>

<ul>
<li>The <var/local home/> factory interface for clients to find
and create beans.
<li>The <var/local/> interface for clients to use.
<li>The <var/implementation/> bean to write business methods.
</ul>

<p>Why three classes? The interfaces add code clarity for the
developer and flexibility for Resin-CMP.  It's conceptually cleaner
to separate the interfaces of the bean from its implementation.  It's
also cleaner to separate the factory pattern interface from the
object interface.  Separating the classes gives Resin-CMP the
flexibility to add its caching and transaction code without
requiring any client changes.</p>

<p>Resin-CMP focuses on <var/local interfaces/>, as
opposed to the <var/remote interfaces/> of traditional EJB.  Local
interfaces are used in a single servlet web-application and avoid the
complexities of distributed computing.  In addition, local interfaces
are faster since they can use normal pass-by-reference Java calls.
In this way, Resin-CMP turns EJB on its head.  EJB is a distributed
computing interface with support for object-managed databases.
Resin-CMP provides an object view to relational database, and has
support for distributed calls for those rare applications which
really need it.</p>

<section title="Local Home Interface">

<p>The home interface is reponsible for factory pattern methods:
finding existing objects and creating new objects.  At minimum, each
home interface lets you find an object using its primary key.
The <code/findByPrimaryKey/> method exists for any entity bean.
Like all the find methods, Resin-CMP will generate the implementation
code and SQL for findByPrimaryKey.  We just need to add the method
to the interface.</p>

<p>Find methods always return the local interface for the bean or a
collection of local interfaces and always throw the FinderException.</p>

<p>Each home interface must extend the EJBLocalHome interface.  Local
home interfaces can only be used same web-application as the server.
This makes it a perfect solution for servlet-based database applications.</p>

<example title="CourseHome.java">
package example.cmp.basic;

import javax.ejb.*;

public interface CourseHome extends EJBLocalHome {
  Course findByPrimaryKey(String name)
    throws FinderException;
}
</example>

</section>

<section title="Local Interface">

<p>The local interface, <code/Course/>, is where all the action is.
We expose three methods to clients, <code/getCourseId/>, <code/getInstructor/>
and <code/setInstructor/>.  Local interfaces always extend
<code/EJBLocalObject/>.</p>

<p>Clients always use the home interface to get the local interface.
The Resin-CMP generated stub (the class implementing the interface)
will call the underlying implementation bean and SQL, adding
transaction management as necessary.</p>

<example title="Course.java">
package example.cmp.basic;

import javax.ejb.*;

public interface Course extends EJBLocalObject {
  String getCourseId();

  String getInstructor();
  void setInstructor(String instructor);
}
</example>

</section>

<section title="Bean Implementation">

<p>Since Resin-CMP provides most of the implementation code, the
Bean implementation just has a bunch of abstract methods.  More
complicated beans will add business methods to the entity bean's
implementation class.  Because business methods run in a single
transaction context, you can use them to ensure database consistency
without having to write any transaction code yourself.</p>

<p>The field accessors are abstract since Resin-CMP will generate the
code to call JDBC and execute the SQL queries.  Like all entity beans,
clients never use a CourseBean directly, but always work through a
stub generated by Resin-CMP.</p>

<p>The AbstractEntityBean class is a convenience class in Resin-CMP.
Each entity bean must implement the EntityBean interface which has
several methods.  Since most applications don't need to customize the
methods, AbstractEntityBean simplifies the implementation code.</p>

<example title="CourseBean.java">
package example.cmp.basic;

public abstract class CourseBean
  extends com.caucho.ejb.AbstractEntityBean {
  public abstract String getCourseId();

  public abstract String getInstructor();
  public abstract void setInstructor(String val);
}
</example>

</section>

<p>With Resin-EJB, all the Java source can be dropped in WEB-INF/classes.
Resin will automatically compile any changes and regenerate the persistence
classes, stubs and skeletons.</p>

</section>

<section title='Deployment Descriptor'>

<p>The deployment descriptor configures the entity bean.  It
specifies the home, local, and implementation classes.</p>

<p>The *.ejb file is generally defined by the bean provider, i.e.
whoever creates the bean.  Later, we'll also need to attach the bean to the
webserver as described in the following section.  Deploying the bean
is as easy as dropping the *.ejb in WEB-INF.  When the web-app
reloads, <code/EJBServer/> will automatically pick up the *.ejb.  (You may need
to force a reload by touching a class file.)</p>

<example title='WEB-INF/cmp-basic.ejb'>
&lt;ejb-jar>
&lt;enterprise-beans>
  &lt;entity>
    &lt;ejb-name><var/basic_CourseBean/>&lt;/ejb-name>
    &lt;local-home><var/example.cmp.basic.CourseHome/>&lt;/local-home>
    &lt;local><var/example.cmp.basic.Course/>&lt;/local>
    &lt;ejb-class><var/example.cmp.basic.CourseBean/>&lt;/ejb-class>

    &lt;prim-key-class><var/String/>&lt;/prim-key-class>
    &lt;primkey-field><var/courseId/>&lt;/primkey-field>

    &lt;persistence-type><var/Container/>&lt;/persistence-type>
    &lt;reentrant><var/True/>&lt;/reentrant>

    &lt;abstract-schema-name><var/courses/>&lt;/abstract-schema-name>
    &lt;sql-table><var/basic_courses/>&lt;/sql-table>

    &lt;cmp-field>&lt;field-name><var/courseId/>&lt;/field-name>&lt;/cmp-field>

    &lt;cmp-field>
      &lt;field-name><var/instructor/>&lt;/field-name>
      &lt;sql-column><var/teacher/>&lt;/sql-column>
    &lt;/cmp-field>
  &lt;/entity>
&lt;/enterprise-beans>
&lt;/ejb-jar>
</example>

<deftable>
<tr><th>Tag<th>Meaning
<tr><td>ejb-jar<td>top-level containing element
<tr><td>enterprise-beans<td>bean provider configuration
<tr><td>entity<td>defines an entity bean
<tr><td>ejb-name<td>The name of the ejb.  Used to tie ejbs together and
used in contructing the url.
<tr><td>local-home<td>class name of the local home interface
<tr><td>local<td>class name of the local interface
<tr><td>ejb-class<td>the bean's implementation class
<tr><td>prim-key-class<td>class of the primary key
<tr><td>persistence-type<td>container persistence in this example
<tr><td>reentrant<td>the bean can call itself
<tr><td>abstract-schema-name<td>abstract name for the bean
<tr><td>sql-table<td>actual SQL table name for the bean

<tr><td>primkey-field<td>which field is the primary key
<tr><td>cmp-field<td>all container managed persistence fields should be listed
<tr><td>field-name<td>the field's name
<tr><td>sql-column<td>the SQL table name for the field
</deftable>

<section title='EJB to SQL Mapping'>

<p><var/abstract-schema-name/> names the abstract table for the entity
bean.  If no other mapping is specified, it will be used for the SQL table.
In the example, it's set to "basic_courses".  If the
abstract-schema-name is missing, Resin-CMP will use the
ejb-name for the database table.  You can add a sql-table to
specify a different SQL table.  sql-table is a Resin-CMP extension.
</p>

<example>
&lt;abstract-schema-name><var/courses/>&lt;/abstract-schema-name>
&lt;sql-table><var/basic_courses/>&lt;/sql-table>
</example>

<p>Database fields are converted from the get and set accessor names
using a beans-like mapping.  "get" is removed and the uppercased
character is lower cased.  Resin-EJB will convert any <code/xY/> pattern to
"x_y".  So <code/getId/> maps to the SQL column "id".  You can
specify a sql-column to specify the SQL column:</p>

<example>
&lt;cmp-field>
  &lt;field-name><var/instructor/>&lt;/field-name>
  &lt;sql-column><var/teacher/>&lt;/sql-column>
&lt;/cmp-field>
</example>

</section>

</section>

<section title="Resin Configuration">

<p>Now that we've built the bean, we need to
attach it to Resin.  The entity bean is deployed using
the <code/EJBServer/> resource.</p>

<example title='WEB-INF/web.xml'>
&lt;web-app>
  &lt;!-- jdbc configuration -->
  &lt;resource-ref>
    &lt;res-ref-name>jdbc/test&lt;/res-ref-name>
    &lt;res-type>javax.sql.XADataSource&lt;/res-type>
    &lt;driver-name>oracle.jdbc.driver.OracleDriver&lt;/driver-name>
    &lt;url>jdbc:oracle:thin:@gryffindor:1521:hogwarts&lt;/url>
  &lt;/resource-ref>

  &lt;!-- server configuration -->
  &lt;resource-ref>
    &lt;res-ref-name>java:comp/env/cmp&lt;/res-ref-name>
    &lt;class-name>com.caucho.ejb.EJBServer&lt;/class-name>
    &lt;init-param data-source="<var/java:comp/env/jdbc/test/>"/>
  &lt;/resource-ref>
&lt;/web-app>
</example>

<deftable>
<tr><th>EJBServer configuration<th>meaning
<tr><td>resource-ref<td>configures a JNDI resource
<tr><td>res-ref-name<td>The JNDI name where the resource will be stored
<tr><td>class-name<td>The name of the bean implementing the resource
<tr><td>init-param<td>bean-style configuration for the resource
<tr><td>data-source<td>JNDI reference to JDBC driver
<tr><th>JDBC tag<th>meaning
<tr><td>resource-ref<td>configures a resource stored in JNDI
<tr><td>res-ref-name<td>the JNDI suffix after the standard java:comp/env
<tr><td>res-type<td>javax.sql.DataSource is for JDBC database drivers
<tr><td>driver-name<td>classname of the driver
<tr><td>url<td>JDBC URL for the driver
</deftable>

<section title='XADataSource'>

<p>The database needs to be configured using <code/XADataSource/> instead
of the usual <code/DataSource/>.  The reason is that <code/XADataSource/>
enables transactions in the database.  <code/DataSource/> is not
transaction aware.  So if there's a
conflict or some other need to roll back the transaction, you need
<code/XADataSource/> and the database's transaction ability to
protect the database consistency.</p>

</section>

</section>

<section title="Client Servlet">

<p>Now that we've defined the EJB, we should go ahead and use it.
Because we haven't defined any method to find all the courses, we
need to know them beforehand.</p>

<p>Because everything is defined in the web.xml, we just need to know
that the <code/CourseHome/> is at <code/java:comp/env/cmp/house/>.  So servlet
code can be completely independent of the server deployment.  Because
the JNDI lookup is relatively slow, applications generally lookup the
Home interface in the <code/init()/> interface and store it as a
servlet variable.</p>

<example title="CourseServlet.java">
package example.cmp.basic;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.ejb.*;

public class CourseServlet extends HttpServlet {
  // cache the home interface so the JNDI only happens once
  private CourseHome home = null;

  public void init()
    throws ServletException
  {
    try {
      // The JNDI context containing local EJBs
      Context cmp = (Context) new InitialContext().lookup("java:comp/env/cmp");

      // Get the house stub
      home = (CourseHome) cmp.lookup("basic_CourseBean");
    } catch (NamingException e) {
      throw new ServletException(e);
    }
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException
  {
    PrintWriter out = res.getWriter();

    res.setContentType("text/html");

    out.println("&lt;h3>Course Details&lt;/h3>");

    String []courses = new String[] { "Potions", "Transfiguration" };

    try {
      for (int i = 0; i < courses.length; i++) {
        // Find the course using the home interface
        Course course = home.findByPrimaryKey(courses[i]);

        out.println("course: " + course.getCourseId() + "&lt;br>");
        out.println("instructor: " + course.getInstructor() + "&lt;br>");
        out.println("&lt;br>");
      }
    }
    catch (FinderException e) {
      throw new ServletException(e);
    }
  }
}
</example>
<results>
<h3>Course Details</h3>
course: Potions
instructor: Severus Snape

course: Transfiguration
instructor: Minerva McGonagall
</results>

</section>

<section title="Conclusion">

<p>The core of Resin-CMP's database management is its management of a
single table.  Much of the work underlying the database management is
hidden from the applicaton.  Transaction management and caching happen
automatically.  For example, once the course has been loaded from the
database, Resin-CMP does not need to query the database again until
the course changes.  So read-only requests, the most common, can avoid
all database traffic.</p>

<p>More complicated applications build on the single table
management.  The following examples add more realistic features to
this example: using queries to <a href="../cmp-find/index.xtp">find all
courses</a> and <a href="../cmp-create/index.xtp">creating</a> new database rows.
</p>

</section>
  </body>
</document>
