Forward: from EJB 2.1 to EJB 3.0

Source: Internet
Author: User
Tags abstract implement interface key table name version xslt jboss application server
Before we begin to discuss how to migrate from EJB 2.1 to EJB 3.0, it's important to understand what happens after the migration: primarily, EJB 3.0 reduces the number of classes, interfaces, and deployment descriptors needed to create EJBS. EJB 3.0 simplifies the EJB development process by replacing the abstract bean class with Pure legacy Java Objects (POJO), replacing components and primary interfaces (Component & Home) with a pure Legacy Java interface (Poji), The latter is optional-you don't have to include them all.

The deployment descriptor,--ejb-jar.xml--, specifies the EJB name, Bean object name, interface, Finder method, container management relationship (CMR), and no more developer-related deployment descriptors are needed here, because they have been superseded by metadata annotations in the component class. This is why you need to use JDK 5.0来 to develop EJB 3.0 applications because they use annotations, and annotations are not available before JDK 5.0.

EJB 3.0 replaces the Finder method in EJB 2.1 with the Javax.persistence.EntityManager API, usually EJB 2.1 of the client application uses the Jndi name to obtain a reference to the entity (entity) and session-bean objects, while the EJB 3.0 client application uses @resource, @Inject, and @ejb.

In EJB 2.1, the JAVAX.EJB wrapper class and interface can be used to develop entity sessions where a session bean implements the Sessionbean interface and an entity bean implements the Entitybean interface; by contrast, EJB 3.0 of sessions and entity bean classes are pojo and do not implement Sessionbean and Entitybean interfaces.

A session bean class of EJB 2.1 specifies one or more ejbcreate methods, callback methods, Setsessioncontext methods, and Business (business) methods; Similarly, an EJB 2.1 entity specifies ejbcreate (), Ejbpostcreate (), callbacks, capacity management persistence (CMP), CMR Getter/setter, and business methods. An EJB 3.0 session Bean class only specifies a business method; Similarly, an EJB 3.0 entity bean specifies only the business method, the Getter/setter method for different bean properties, and the Getter/setter method of the bean relationship.

The EJB 2.1 main interface extends the Javax.ejb.EJBHome interface, and another local main interface extends the Javax.ejb.EJBLocalHome interface; EJB The 2.1 remote interface extends the Javax.ejb.EJBObject interface, and another local interface extends the Javax.ejb.EJBLocalObject interface. In EJB 3.0, the component and the primary interface are not specified-they have been replaced by Poji, and if a session bean class does not specify a business interface, the EJB server will generate a Poji business interface for it from the session Bean class.

Remember these changes in your mind, and in the next section of this article, you will focus on two examples of the details needed to migrate a session bean and an entity bean from EJB 2.1 to EJB 3.0.

   Migrating Session Beans

The EJB 2.1 Session Bean class--bookcatalogbean--in the example specifies a Ejbcreate method, a business method called GetTitle (), and a callback method:

Bookcatalogbean.java
Import Javax.ejb.SessionBean;
Import Javax.ejb.SessionContext;

public class Bookcatalogbean implements Sessionbean
{
Private Sessioncontext CTX;
public string Getedition (string title)
{
if (Title.equals ("Java & XML"))
return new String ("second version");
if (Title.equals ("Java and XSLT")
return new String ("first version");
}
public void Ejbcreate () {}
public void Ejbremove () {}
public void Ejbactivate () {}
public void Ejbpassivate () {}
public void Setsessioncontext (Sessioncontext ctx)
{this.ctx=ctx;}
}
In an EJB 3.0 session bean, you can use metadata annotations to specify the bean type, that is, to specify either stateful (stateful) or stateless (stateless) using @stateful and @stateless respectively. You can also use a business interface in a session bean to replace the component with the primary interface, because the business interface is a Poji, so you can specify it as a local or remote type using @local and @remote, and a session bean can implement both local and remote interfaces simultaneously.

If you do not specify an interface type (local or remote) in the Bean class, the EJB server automatically generates a local business interface by default, where you can also use @local and @remote annotations to specify the interface class.

The following EJB 3.0 session Bean is a pojo that is ported from the previous Bookcatalogbean.java EJB 2.1 stateless session bean, noting that it uses @stateless annotations to implement a local business interface, The local interface class name is specified in the @local annotation.

Bookcatalogbean.java EJB 3.0 Session Bean
@Stateless
@Local ({Bookcataloglocal.java})
public class Bookcatalogbean implements
Bookcataloglocal
{
public string Getedition (string title)
{
if (Title.equals ("Java & XML"))
return new String ("second version");
if (Title.equals ("Java and XSLT")
return new String ("first version");
}
}


Also, note that the above EJB 3.0bean class replaces the component in EJB 2.1 with the primary interface with a local business interface (Poji) through the @local annotation.

   migrating EJB Session Bean clients

A client of an EJB 2.1 session Bean can get a session bean object by using the Jndi name, as shown by the client using the Bookcataloglocalhome Jndi name to get a local host object, then invoking the Create () method, and then The client uses the Getedition (String) business method to output the version value of a particular caption.

Import Javax.naming.InitialContext;
public class Bookcatalogclient
{
public static void Main (string[] argv)
{
try{
InitialContext ctx=new InitialContext ();
Object objref=ctx.lookup ("Bookcataloglocalhome");
Bookcataloglocalhome cataloglocalhome = (bookcataloglocalhome) ObjRef;
Bookcataloglocal cataloglocal = (bookcataloglocal) cataloglocalhome.
Create ();
String title= "Java and XML";
String Edition = Cataloglocal.getedition (title);
System.out.println ("title version:" + title + "" + edition);
}
catch (Exception e) {}
}
}
In EJB 3.0, Dependency injection can be used to get a reference to the session bean object, which is usually implemented by @inject, @Resource, @EJB annotations. The EJB 3.0 session Bean client, as shown below, is injected into the Bookcatalogbean class using the @inject annotation, and can still be obtained by the Getedition (String) Business method to obtain the version value of the header.

public class Bookcatalogclient
{
@Inject Bookcatalogbean;
Bookcatalogbean Catalogbean;

String title= "Java and XML";
String edition=catalogbean.getedition (edition);
System.out.println ("title version:" + title + "" + edition);
}
   Migrating entity Beans

This section describes how to migrate entity beans for EJB 2.1 to EJB 3.0. An EJB 2.1 entity bean implements the Entitybean interface, which consists of getter and setter CMP field methods, getter and setter CMR field methods, callback methods, and Ejbcreate/ejbpostcreate methods. The sample entity bean (see Example 1),--bookcatalogbean.java, consists of CMP field headers, author, publisher, and CMR field versions.

Case 1:bookcatalogbean.java

Import Javax.ejb.EntityBean;
Import Javax.ejb.EntityContext;

public class Bookcatalogbean implements Entitybean
{
Private Entitycontext CTX;
public abstract void Settitle ();
Public abstract String getTitle ();
public abstract void Setauthor ();
Public abstract String Getauthor ();
public abstract void Setpublisher ();
Public abstract String Getpublisher ();
public abstract void Seteditions (Java.util.Collection editions);
Public abstract java.util.Collection geteditions ();

public string Ejbcreate (string title)
{
Settitle (title);
return null;
}

public void Ejbremove () {}
public void Ejbactivate () {}
public void Ejbpassivate () {}
public void Ejbload () {}
public void Ejbstore () {}

public void Setentitycontext (Entitycontext ctx)
{
This.ctx=ctx;
}

public void Unsetentitycontext ()
{
CTX = null;
}
}
The EJB 2.1 entity Bean's Ejb-jar.xml deployment descriptor (see Example 2) file specifies the EJB class, interface, CMP field, EJB QL query, and CMR relationship. The Bookcatalogbean entity Bean defines a lookup method Findbytitle (), a CMR field, and a version.

Example 2:ejb-jar.xml Deployment Descriptor

<?xml version= "1.0"? > >
! DOCTYPE Ejb-jar Public
"-//sun Microsystems, Inc.//dtd Enterprise JavaBeans 2.0//en"
"Http://java.sun.com/dtd/ejb-jar_2_0.dtd" >
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name> Bookcatalog </ejb-name>
<local-home> Bookcataloglocalhome </local-home>
<local> bookcataloglocal </local>
<ejb-class> Bookcatalogbean </ejb-class>
<persistence-type> Container </persistence-type>
<prim-key-class> String </prim-key-class>
<reentrant> False </reentrant>
<cmp-version> 2.x </cmp-version>
<abstract-schema-name> Bookcatalog </abstract-schema-name>
<cmp-field>
<field-name> title </field-name>
</cmp-field>
<cmp-field>
<field-name> author </field-name>
</cmp-field>
<cmp-field>
<field-name> Publisher </field-name>
</cmp-field>
<query>
<query-method>
<method-name> Findbytitle </method-name>
<method-params>
<method-param> java.lang.String </method-param>
</method-params>
</query-method>
<ejb-ql>
! [Cdata[select DISTINCT OBJECT (obj) from Bookcatalog obj WHERE obj.title = 1]]>
</ejb-ql>
</query>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relation-name> bookcatalog-editions </ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>
Bookcatalog-has-editions
</ejb-relationship-role-name>
<multiplicity> One </multiplicity>
<relationship-role-source>
<ejb-name> Bookcatalog </ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name> Editions </cmr-field-name>
<cmr-field-type> java.util.Collection </cmr-field-type>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>
Editions-belong-to-bookcatalog
</ejb-relationship-role-name>
<multiplicity> One </multiplicity>
<cascade-delete/>
<relationship-role-source>
<ejb-name> Edition </ejb-name>
</relationship-role-source>
</ejb-relationship-role>
</ejb-relation>
</relationships>
</ejb-jar>

In contrast, the EJB 3.0 entity Bean class that corresponds to the EJB 2.1 entity Bean class is a plain old Java object (POJO) and very simple (see Example 3). The EJB 3.0 version of this bean class uses the metadata annotation @entity, and the EJB 2.1 Department descriptor ejb-jar.xml The lookup method specified by the element character in the file, in the EJB 3.0 Bean class, The CMR relationship specified by the element character in the Ejb-jar.xml file is specified using the @namedqueries and @namedquery annotations, specified in the EJB 3.0 bean class by a metadata annotation, and the primary key field is specified by the @id annotation. Some of the metadata annotations for EJB 3.0 are listed in Table 1.

Case 3:bookcatalogbean.java

Import javax.persistence.Entity;
Import Javax.persistence.NamedQuery;
Import Javax.persistence.Id;
Import Javax.persistence.Column;
Import Javax.persistence.OneToMany;

@Entity
@NamedQuery (name= "Findbytitle", querystring =
"Select DISTINCT OBJECT (obj) from Bookcatalog obj WHERE obj.title =? 1")

public class Bookcatalogbean
{
Public Bookcatalogbean () {}
Public Bookcatalogbean (String title)
{
This.title=title;
}

Private String title;
Private String author;
Private String publisher;

@Id
@Column (name= "title", primarykey= "true")

Public String GetTitle () {return title;}
public void Settitle () {this.title=title;}
public void Setauthor (String author) {This.author=author;}
Public String Getauthor () {return author;}
public void Setpublisher (String publisher)
{
This.publisher=publisher;
}
Public String Getpublisher () {return publisher;}
Private java.util.Collection <Edition> Editions;

@OneToMany
public void Seteditions (Java.util.Collection editions)
{
This.editions=editions;
}

Public Java.util.Collection geteditions () {return editions;}
}
Table 1:EJB 3.0 Common Meta data annotations

Comments Description annotation element
@Entity Indicate an entity Bean class.
@Table Note the Entity Bean table. If @table is not specified, the table name is the same as the EJB name. Name, schema
@Id Indicate a major key attribute or field.
@Transient Indicate a Non-persistent property or field.
@Column Specify a mapping bar for a persistent entity bean property. Name, PrimaryKey, nullable, length. The default column name is the property or field name.
@NamedQueries Indicate a set of named queries.
@NamedQuery Indicate a named query or a query related to the lookup method. Name, querystring
@OneToMany Indicate a one-to-many connection. Cascade
@OneToOne Indicate a one-to-one contact. Cascade
@ManyToMany Indicate a many-to-many connection. Cascade
@ManyToOne Indicate a many-to-many connection. Cascade

The lookup method in the EJB 2.1 Bean Class Findbytitle (), the corresponding @namedquery annotation is used in EJB 3.0, the CMR relationship in the EJB 2.1 entity Bean, and the @onetomany annotation is used in the EJB 3.0 entity bean. Note @id The identifier attribute caption, @column Specifies the database column that corresponds to the Identifier property title. If a persistent entity bean property is not marked with @column, the EJB server assumes that the column name is the same as the Entity Bean property name. Transient entity bean properties are usually indicated by @transient.

Migrate EJB entity Bean clients

You can create an EJB 2.1 entity bean main object or a native object by using the Create () method in the Entity Bean Master Interface or the local landlord interface. Typically, a client of an EJB 2.1 entity Bean can obtain a local or remote object of an entity bean through a jndi lookup. Here is a sample code that creates a local main object for an EJB 2.1 entity bean.

InitialContext ctx=new initialcontext ();
Object objref=ctx.lookup ("Bookcataloglocalhome");
Bookcataloglocalhome cataloglocalhome = (bookcataloglocalhome) ObjRef;
in the preceding code snippet, Bookcataloglocalhome is the jndi name of the Bookcatalogbean entity bean.

After a reference is received, the client of EJB 2.1 creates a local object through the Create () method.  

Bookcataloglocal cataloglocal = (bookcataloglocal)
Cataloglocalhome.create (title);
In EJB 2.1, a local or remote object can be obtained from a local host object by looking for a method. For example, you can get a local object by using the Findbyprimarykey method as shown below.  

Bookcataloglocal cataloglocal = (bookcataloglocal)
Cataloglocalhome.findbyprimarykey (title);
  Additionally, in EJB 2.1, you can remove an instance of an entity bean using the Remove () method:

Cataloglocal.remove ();
EJB 3.0 implements persistence, lookup, and removal through the Javax.persistence.EntityManager class. Table 2 lists some of the common methods used in the Entitymanager class to replace the EJB 2.1 method.

Table 2:entitymanager class methods

Entitymanager method Describe
Persist (Object entity) Make an entity bean instance persistent.
Createnamedquery (String name) Create an instance of the query object to execute the named query.
Find (Class entityclass, Object PrimaryKey) Finds an entity bean instance.
CreateQuery (String ejbql) Create a query object to run the EJBQL query.
Remove (Object entity) Removes an instance of an entity bean.

In the client class of an EJB 3.0 entity bean, you can inject the Entitymanager object using the @resource annotation.

@Resource
Private Entitymanager em;
You can call the Entitymanager.persist () method to persist an instance of an entity bean, for example:

Bookcatalogbean Catalogbean = new Bookcatalogbean (title);
Em.persist (Catalogbean);
Similarly, you can call the Entitymanager.find () method to obtain an instance of an entity bean.
 
Bookcatalogbean Catalogbean = (Bookcatalogbean)
Em.find ("Bookcatalogbean", title);
You can also define an EJB 3.0 client class lookup method that is equivalent to named Query Findbytitle (unlike the lookup method in EJB 2.1) and get a query object using the Createnamedquery (String) method.

Query query=em.createnamedquery ("Findbytitle");
Set the parameters of the query object with the Setparameter (int paramposition, string paramvalue) or Setparameter (string parametername, String value) method. Note that the parameter position here starts at 0.

Query.setparameter (0, title);
Using the Query.getresultlist () method to obtain a collection of Bookcatalogbean objects, you can use the Getsingleresult () method instead if you are sure that the query returns only a single result.

Java.util.Collection catalogbeancollection = (Bookcatalogbean) query.getresultlist ();
Finally, an instance of the entity bean is removed using the Entitymanager.remove (Object entity) method.

Bookcatalogbean Catalogbean;
Em.remove (Catalogbean);
Example 4 demonstrates a stateless session bean customer class for a complete EJB 3.0 entity bean.

Example 4:bookcatalogclient class

Import javax.ejb.Stateless;
Import Javax.ejb.Resource;
Import Javax.persistence.EntityManager;
Import Javax.persistence.Query;

@Stateless
@Local
public class Bookcatalogclient implements Bookcataloglocal
{
@Resource
Private Entitymanager em;

public void Create (String title)
{
Bookcatalogbean catalogbean=new Bookcatalogbean (title);
Em.persist (Catalogbean);
}
Public Bookcatalogbean Findbyprimarykey (String title)
{
Return (Bookcatalogbean) em.find ("Bookcatalogbean", title);
}

Public java.util.Collection Findbytitle (String title)
{
Query query=em.createnamedquery ("Findbytitle");
Query.setparameter (0, title);
Return (Bookcatalogbean) query.getresultlist ();
}

public void Remove (Bookcatalogbean catalogbean)
{
Em.remove (Catalogbean);
}
}
The above example shows how to migrate a session bean and entity bean from EJB 2.1 to EJB 3.0, and this is similar to migrating from EJB 2.0.

When this article was finalized, there were some application servers that supported the EJB 3.0 specification, such as the JBoss application Server, the Oracle Application Server, and the Caucho application server. Unfortunately, the implementation of EJB 3.0 is different for these application servers----they may not implement all of the EJB 3.0 features, so be sure to read the documentation provided by the application server carefully before you start writing the program.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.