Introducing CMP create(...) methods.

Create methods for CMP beans are conceptually similar to constructors for regular JavaBeans. By calling a create method, you create a new persistent entity.

The following example uses this schema:

  DROP TABLE create_courses;
  CREATE TABLE create_courses (
    course_id VARCHAR(250) NOT NULL,
    instructor VARCHAR(250),

    PRIMARY KEY(course_id)
  );

  INSERT INTO create_courses VALUES('Potions', 'Severus Snape');
  INSERT INTO create_courses VALUES('Transfiguration', 'Minerva McGonagall');
  INSERT INTO create_courses VALUES('Defense Against the Dark Arts', 'Remus Lupin');
  

Defining create(...) methods

A bean is not required to have any create(...) methods. You can however specify any number of them (each with a different signature).
To declare a new create(...) method you need to change two files; the home interface and the bean implementation class. The deployment descriptor is not modified.

In the home interface, CourseHome.java, you declar the create method and have it throw a javax.ejb.CreateException:


  public Course create(String courseId, String instructor)
    throws CreateException;
  
In the bean implementation class, CourseBean.java, you need to declare two methods corresponding to the create(...) method above. ejbCreate(...) contains any code you want to execute when you create a new Entity. You don't have to initialize all values, but it is mandatory to initialize the primary key.:

  public String ejbCreate(String courseId, String instructor)
    throws CreateException
  {
    setCourseId(courseId);
    setInstructor(instructor);
    return null;
  }
  
ejbPostCreate(...) is called by the container after the code in the corresponding ejbCreate(...) method has executed.

  public void ejbPostCreate(String courseId, String instructor)
  {
  }
  

Using the create(...) method

Once you have written all the neccessary code, using your create(...) method is as simple as this:


  Course divination;
  try {
    divination = home.create("Divination", "Sybil Trelawney");
  } catch(CreateException e) {
  }