Introduction to EJB 3.0

Source: Internet
Author: User
Introduction to EJB 3.0Admin | 16 August 15, 2006

Sun China Software Technology Center Wang Qiang wynne.wang@sun.com

1. Simplified development goals

1.1 our goal

Ejb3.0 is a topic that many people are talking about at present. The key to enterprise software development is to provide an application framework that is as simple as possible: it allows developers to ignore complex issues, such as transaction processing, security, and persistence. You can focus on business logic rather than lower-layer technical details to improve developers' efficiency and produce high-quality software. This is also the goal of formulating the EJB 3.0 specification to simplify development!

1.2 Current Problem

Ejb3.0 hopes developers can benefit from this new development model and better promote J2EE applications. with the continuous development of Java, more and more enterprises choose J2EE as their solutions. The J2EE architecture provides a simplified middle-layer integration framework to meet application requirements. However, for general developers, the EJB 1.4 framework under J2EE 2.1 is too complicated. According to the definition of ejb2.1 specification, the EJB component must have many interfaces in advance, such as the home interface, remote interface, and local interface, and define many XML Description files for various application types. To access a component or service, you must use jdni to search for the service and bind the service by name to find the target object.

For example, if we want to use an EJB shopping cart, we need to first implement an initial context, then use it to find the home interface of this EJB, and then call the create method of the home interface to obtain an EJB object, finally, call the business method of this EJB object. the following is an example:
// Ejbs 2.1 Client view of the shoppingcart Bean
...
Context initialcontext = new initialcontext ();
Shoppingcarthome mycarthome = (shoppingcarthome)
Initialcontext. Lookup ("Java: COMP/ENV/EJB/cart ");
Shoppingcart mycart = mycarthome. Create ();
// Use the bean
Collection widgets = mycart. starttoshop (widgets)
...
// Don't forget code to handle javax. EJB. createexception
...
The ejb2.1 specification also requires that we must implement the interfaces defined in javax. EJB to implement methods such as ejbcreate (), ejbpassivate (), and ejbactivate (). In most cases, these methods do not need to be modified by developers. These regulations have nothing to do with the true core business logic. They are only some technical templates that require developers to develop based on these templates. For example, the following code:

People begin to think about how to make EJB development easier and make better use of this technology. the current EJB 3.0 standard aims to simplify development and attract more developers to enjoy its ease of use and powerful functions. To achieve this goal, the first and most important thing to do is to simplify the use of EJB from the perspective of a developer.

1.3 Work of the JCP Expert Group

This task was completed by the ejb3.0 expert group. We know that Java development and promotion are completed by an open organization named Java Community process. JCP. sun's philosophy is that innovation is everywhere. therefore, the JCP team listened to Java suggestions from every corner of the world and determined the requirements of various parties in the form of Java specification requests. the JSR Number of the EJB 3.0 specification is 220. members of the entire Expert Group include registered J2EE users, developers of application servers, and members of the J2EE community.

Simplifying an existing technology, especially those widely supported by developers, such as EJB is not a simple task. as a foreshadowing, the expert group has made a lot of preparations, tested the complexity of the EJB technology, the various modes and anti-modes popular in the current EJB watershed, and various requirements from customers and developers. Developers and users hope that EJB can provide satisfactory features based on their actual needs.
The test results show that in most cases, people do not need more advanced technologies, but need more simplified technologies to simplify the current development model. Instead of increasing the technical complexity like the previous EJB release. Defining a new technology not only updates the old technology, but also supports the old technology to provide backward compatibility. because enterprises adopting these technologies have invested a lot in these technologies. if the corresponding IT system and data become unusable due to technical updates, it is a very bad thing.

Therefore, it is necessary to support the existing EJB technology while defining the ejb3.0 specification. to ensure that the existing ejb api is continuously available, and to work with the new ejb3.0 API, we should continue to provide support for earlier APIs instead of marking them as not in favor of use.

1.4 New Annotation Functions

Many new features of ejb3.0 are implemented through Java se5.0. Here we will talk about Java SE 5.0, which provides many features. The most interesting one is the annotation function. We know that the previous Java language is in command format, such as. B () indicates that Class A is allowed to do thing B, but many times we only need to make some annotations to an object, such as marking a class as a serializable. this is only a tag. For future processing instructions, you do not need to perform any operations.
During deploy, many XML files are provided, such as the description file, which describes the referenced EJB name, interface, and transaction type of the current EJB. all this information is descriptive, not imperative. it is used to explain a property of an object. therefore, there is a very interesting idea. Can I extend the Java language and combine the advantages of annotation and command?

This is also done by an expert group within the JCP organization. The JSR specification number is JSR 175, which supports the annotation function for Java SE 5.0. this specification provides some basic and critical support for the simplified implementation of ejb3.0. the annotation can have its own attributes or define its own duration, indicating whether the information is saved to the source code, whether it persists to the class, or whether it remains to the running time. the annotation has its own default value. in most cases, we can estimate the behavior of this object without explaining it.
2. Easy implementation and development

2.1 reduce the burden on developers

The simplified work of ejb3.0 includes the following parts:
Provides a simplified API, including the definition of EJB and the reference of EJB.
Reduces the number of classes for development and eliminates the need for so many interfaces.
Correlation Injection
Simplified query Mechanism
From the developer's point of view, there is no need to use the deployment description file. A lot of work can be done in the Code with annotations, such as the transaction type of entity bean.
Simplified persistence
Simplifies and improves o/R Mapping of data objects.

Annotations can be applied to some basic elements of programming languages, such as classes, methods, variables, and packages. when we use these annotations in the code, according to the corresponding persistence policy of the annotation, it can be compiled into the class file, or it can be maintained until it is run. Most of the labels defined in EJB 3.0 are runtime persistence policies. The advantage of doing so is that they provide maximum flexibility. In addition, because a large amount of work is put into operation, it also reduces some of the work of deploy.

We define the default syntax to illustrate most common cases. Developers do not need to specify common situations. "OK, no problem. The default settings can meet the requirements." This greatly reduces the workload of developers.
This also leads to an interesting concept in ejb3.0 "configuration by exception" -- we only need to participate in the exception.

Ejb3.0 aims to simplify the work of developers, so that they can focus on business application development rather than focusing on a lot of tedious routine work, which can be done by container. Ejbs use injection to specify the resources they need. They do not need to write any more troublesome methods. They can create and obtain objects and extract them to the outside. The required components are provided by external containers. In this way, developers only need to define it at the beginning, saying that I need this resource, and then I can directly use this resource, which will greatly simplify development, because developers only care about how to use this object and business method, rather than worrying about other technical details.

2.2 put aside tedious details
Let's take a look at the simplification. Our purpose is to hide the complicated technical details. program developers only care about their own business logic code, rather than the complicated technical templates and required interfaces, even if these methods and interfaces do not need to be implemented at all.

Part interfaces of EJB are no longer required
Every EJB is just a common Java class.
You no longer need the home interface. We no longer use home to create this EJB.
No longer need to implement javax. EJB. javasisebean excuses
For the part that needs to be implemented in the callback method, we use the annotation method to describe a callback method.
Complex JNDI name calling mechanism is no longer required.
We adopt the correlation injection method, and we can also use the simplified lookup method to find resources.

Let's look at a simple example of stateless sessionbean. Stateless Session Bean is the simplest and most commonly used bean. Many beginners start with stateless Session Bean. How to Make stateless Session Bean easy to use becomes a very meaningful topic.

We have already defined related interfaces. The ejb2.1 function is to process employees' salaries, open a database connection, and perform some operations on employees' salary information.

// Ejbs 2.1
Public class payrollbean implements javax. EJB. sessionbean
{
Sessioncontext CTX;
Datasource empdb;
Public void setsessioncontext (sessioncontext CTX ){
This. CTX = CTX;
}
Public void ejbcreate (){
Context initialcontext = new initialcontext ();
Empdb = (datasource) initialcontext. Lookup (Java: COMP/ENV/jdbc/empdb );
}
Public void ejbactivate (){}
Public void ejbpassivate (){}
Public void ejbremove (){}
Public void setbenefitsdeduction (INT empid, double deduction ){
...
Connection conn = empdb. getconnection ();
...
}
...
}
// Note deployment descriptor needed

Here we first need to implement a sessionbean interface to maintain a reference to sessioncontext, and then call jndi in the ejbcreate method to obtain a datasource. Some callback methods must be defined later, although these methods do not implement any logic. Then, in the business method, we open a database connection.

Note that we are not finished yet. To use this EJB, you must add the XML deployment description file to pack it.

The following is a common deployment description file.

<Session>
<EJB-Name> payrollbean </EJB-Name>
<Local-Home> payrollhome </Local-Home>
<Local> payroll </local>
<EJB-class> com. example. payrollbean </EJB-class>
<Session-type> stateless </session-type>
<Transaction-type> container </transaction-type>
<Resource-ref>
<Res-ref-Name> JDBC/empdb </RES-ref-Name>
<Res-ref-type> javax. SQL. datasource </RES-ref-type>
<Res-auth> container </RES-auth>
</Resource-ref>
</Session>
...
<Assembly-Descriptor>
...
</Assembly-Descriptor>

From the developer's perspective, it is very meaningful to check such a simple EJB. We can better understand where there are changes. One major problem is that after so many methods and structures are defined, program clarity is affected and the structure becomes chaotic. The business methods that really need attention are not well emphasized and reflected.

Let's take a look at how EJB 3.0 implements a simple stateless Session Bean.

// Same example, ejbs 3.0
@ Stateless public class payrollbean implements payroll {
@ Resource datasource empdb;
Public void setbenefitsdeduction (INT empid, double deduction ){
...
Connection conn = empdb. getconnection ();
...
}
...
}

@ Stateless annotation indicates that this is a stateless Session Bean. Using this annotation can make it unnecessary to use the sessionbean interface, which greatly simplifies the implementation class of EJB. The commercial interface of bean is payroll. this is a common Java interface. by default, container will make it a local interface. to implement a remote interface, you only need to define another annotation @ remote. note that you do not need to define remoteexceptions in the interface. It is processed by the iner layer later.

2.3 New Method for referencing objects
In the old EJB specification, another complicated aspect is access to the environment object. To access the environment in EJB 2.1, you must first reference the dependency defined by the component, such as resource-Refs and EJB-Refs, and then configure these environment objects in the JNDI namespace. Finally, search for the Environment objects in the JNDI space at runtime.
EJB 3.0 provides two simplified solutions:

1) Correlation Injection
2) A simplified lookup Method

Correlation injection is a technology. Developers Add a annotation definition in the original code, indicating that this environment object is required, and then the container injects the real environment object into it during initialization.
Currently, ejb3.0 spec has two injection methods: setter injection and Variable Injection. These may change in future specifications, such as a unified injection method. We can define an EJB reference through the injection mark @ EJB, or inject the mark @ resource to indicate that we want to reference a resource, which can be any environment object other than EJB. in order to simplify development as much as possible, the Expert Group simplified the use of injected object types.

Ejb3.0 will still provide a dynamic query method, but from the perspective of program developers, you do not need to use the jndi api, but instead use the lookup method of the more simplified EJB context.

In the new EJB 3.0 specification, complex home interfaces and EJB interfaces are no longer required. The EJB client encoding is also greatly simplified, which is no different from accessing a common Java object. Compared with the ejb2.1 example above, it is very simple to use an EJB in EJB 3.0. Only two lines of code are required:

// Ejbs 3.0 client View
@ EJB shoppingcart mycart;
...
Collection widgets = mycart. starttoshop (widgets );
...

First define an EJB application, and then you can directly call the business method of this EJB. The rest of the work is done by container for us.

2.4 new transaction management

The transaction management in EJB greatly simplifies user development programs. The application is divided into a small unit called transaction. The transaction system ensures that the tasks in the unit are complete, either completely executed, or completely returned to the initial state after an error.

There are two types of transactions in J2EE: container-managed transactions and bean-managed transactions. They are different in how to start and end transactions. Transactions managed by bean are explicitly started and ended by the component using the usertransaction class. In the code, you must call the methods usertransaction. Begin () and usertransaction. Commit (). The items managed by the container are automatically completed by the container.
You can define six different transaction attributes for different transaction types.
The transaction attribute tells the container whether to put the work in the EJB method into the user's transaction. Restart a new transaction for this method, or execute this method instead of including it in the transaction.
In the ejb3.0 specification, the default definition is a container-managed transaction. the required transaction attribute is applied to all bean methods. It means that if the application that calls this method does not have transaction environment, this method will automatically create a new one.
Developers can use the annotation method to specify the transaction attribute for the entire EJB or a specific method.
First, let's take a look at the example of a wage processing EJB, which is a standard EJB 3.0 stateless Session Bean. By default, each method is managed by the container, and the default transaction attribute is required.
// Uses container-managed transction, required attribute
@ Stateless public payrollbean implements payroll {
Public void setbenefitsdeduction (INT empid, double deduction ){...}
Public double getbenefitsdeduction (INT empid ){...}
Public double getsalary (INT empid ){...}
Public void setsalary (INT empid, double salary ){...}
}

The following is an example. We know that changes to important data are always very sensitive. For example, if we modify the income tax of a user while changing the salary of a user, we hope these two calls will happen in the same transaction.

@ Stateless public payrollbean implements payroll {
@ Transactionattribute (mandatory)
Public void setbenefitsdeduction (INT empid, double deduction ){...}
Public double getbenefitsdeduction (INT empid ){...}
Public double getsalary (INT empid ){...}
@ Transactionattribute (mandatory)
Public void setsalary (INT empid, double salary ){...}
}

The method for calling the user's salary change must be in an existing transaction environment
To this end, we use @ transactionattribute (mandatory) to mark this method must be in the transaction of a client. If the client does not have such a transaction context, the container will throw a javax. EJB. error message of ejbtransactionrequiredexception.

 

2.5 New Security Mechanism
The EJB architecture does not encourage developers to implement security mechanisms in the form of code. Instead, it uses security roles to define accessible security roles to restrict access permissions to a method.

By default, all methods in 3.0 are "unchecked ". That is to say, security control policies are not required for all methods by default. If the client that calls a method has a user role, we can determine whether this method also follows this role. By default, the security policy is "Caller identity". That is to say, the role of the caller should be consistent with the role of the caller.

This is an example of the security implementation of EJB 3.0. We have not set any security policies for other methods. However, to set the salary of an employee, only the administrator of the personnel department can call this method with high security requirements. We use

@ Rolesallowed ("hr_payrolladministrator ")
// Security View
@ Stateless public payrollbean implements payroll {
Public void setbenefitsdeduction (INT empid, double deduction ){...}
Public double getbenefitsdeduction (INT empid ){...}
Public double getsalary (INT empid ){...}
// Salary setting is intended to be more restricted
@ Rolesallowed (hr_payrolladministrator)
Public void setsalary (INT empid, double salary ){...}
}

2.6 Event Notification and check

In ejbs 3.0, developers do not need to implement unnecessary callback methods. You can specify any method as an event notification method. By marking a notification annotation, we mark a method as a callback method, for example:

@ Stateful public class accountmanagementbean
Implements accountmanagement {
Socket Cs;
@ Postconstruct
@ Postactivate
Public void initremoteconnectiontoaccountsystem {
...
}

@ Predestroy
@ Prepassivate
Public void closeremoteconnectiontoaccountsystem {
...
}
...
}

In this example of EJB 3.0, we defined a stateful session bean, and handed over the initialization work to the init remote connection method, and marked it as a callback method. In construct, and activite.
At the same time, we will hand over the cleanup work to the close remote connection method, mark it as a callback method, and call it before destroy and passivate.

For those advanced users, You need to customize their own event check and listening mechanisms. The check method and the checked object method can be in the same bean or in different Java classes. This check mechanism has the following features:
Check around the Method
The entire call process for packaging business methods
You can process the parameters and results of a method call.
Check the sequence of classes to obtain the context data.
Multiple check classes can be executed in the specified order
You can use deployment specifiers to specify the execution sequence.

We use @ interceptors to specify an external check method class, and use @ aroundinvoke to specify an internal method as the check method. In the check method, we use proceed () to call a specific business method. The current check method is to check all the methods in a bean. The Expert Group is developing a standard so that it can be specific to the check method.

The following is an example of an ejb3.0 check method:

We have developed this stateless Session Bean check method class to be these three classes.
Accountaudit, metrics, and customsecurity. The actual execution will follow the specific sequence.
Check.

@ Interceptors ({
Com. Acme. accountaudit. Class,
Com. Acme. Metrics. Class,
Com. Acme. customsecurity. Class
})
@ Stateless
Public class accountmanagementbean
Implements accountmanagement {
Public void createaccount (INT accountid, details ){...}
Public void deleteaccount (INT accountid ){...}
Public void activateaccount (INT accountid ){...}
Public void deactivateaccount (INT accountid ){...}
...
}

2.7 priority of deployment description files

In ejb3.0, we can use the annotation method to specify the reference to the environment object, or use the deployment description file to define the application to the environment object, you can also use both. if the environment object is set in the deployment description file and code annotation, the reference in the deployment description file has a higher priority, in this way, the deployer of the application is relatively flexible to control.

3. Magic of persistence


3.1 initial goal

Another goal of the EJB 3.0 Expert Group is to provide a lightweight model for ing between entity beans and objects/relationships. In fact, there is a lot of debate on the entity bean, and many critics are dissatisfied with its architecture. Our goal is to improve the persistence model of EJB container management, draw inspiration from some excellent open-source software from various places, and draw experience from some anti-pattern, so that new standards are known as technical leaders. The persistence of ejb3.0 includes the following features:

Simplify Entity Bean programming and reduce unnecessary development Interfaces
Improves EJB persistence and provides inheritance and polymorphism information for o/R ing.
Entity Bean can be used outside EJB container
Commercial methods can be tested without the need for iner
Design pattern is no longer required for data transmission objects such as DTO (data transfer objects)
Improved EJB QL

To solve these problems, the EJB 3.0 Expert Group has concentrated on a simplified persistence model. Currently, similar products and models such as Hibernate and toplink are available in the industry. This is a brand new direction, represents a lightweight object/Link (O/R) ing model.

In ejb3.0, the Entity Bean is a common Java class, which is a real class rather than an abstract class. In addition, developers no longer need to implement any interfaces, whether it is a business excuse or a callback interface.
In addition, you no longer need to implement the data transmission object (DTO), because the current Entity Bean itself is a simple and common Java object pojo (plain old Java object ), after being marked as serialized, it can be passed on the client and server without special processing.

3.2 management roles
In the new ejb3.0 specification, we see an entitymanager class. For an Entity Bean, This is a role similar to calling a factory or a unified home interface. The lifecycle of Entity Manager can be managed by the container or application.
Entity Manager will be responsible for tracking the status of Entity Bean objects in the context of database transactions. For developers, javax. Persistence. entitymanager becomes a unified access point for entity beans. We can regard it as a "home" for Entity Bean operations. We need to use Entity Manager to call the lifecycle management of entity beans. For example, persist, remove, merge, flush, refresh, and other methods.

Entity Manager is the persistent management interface of all entity beans. Any operation on Entity Bean must be performed through it. Some developers will be familiar with this interface because it is very similar to the session interface of Hibernate and the persistence manager of JDO. The Entity Manager interface mainly uses the following methods:

Package javax. EJB;

Public interface entitymanager {
Public void create (Object entity );
Public <t> T Merge (T entity );
Public void remove (Object entity );
Public object find (string entityname, object primarykey );
Public <t> t find (class <t> entityclass, object primarykey );
Public void flush ();
Public query createquery (string ejbqlstring );
Public query createnamedquery (string name );
Public query createnativequery (string sqlstring );
Public void refresh (Object entity );
Public void evict (Object entity );
Public Boolean contains (Object entity );
}

Entitymanager greatly facilitates the implementation of search methods. Remember how we did it in ejb2.1? In EJB 3.0, you can directly call entitymanager. Find (string entityname, object primarykey) to find the Entity Bean instance with a primary key. For example:

Public orderbean findbyprimarykey (string orderid)
{Return (orderbean) Em. Find ("orderbean", orderid );
}

Entitymanager is the production factory of query objects. You can use createquery (string ejbqlstring) to create an ejb ql query, or use createnamedquery (string queryname) to create a namedquery query. The following is an example:

Public list findwithaddr (string ADDR ){
Return em. createquery (
"Select O from orders O where O. ADDR like: orderaddress ")
. Setparameter ("orderaddress", ADDR)
. Setmaxresults (100)
. Listresults ();
}

3.3 o/R Mapping Annotation

The metadata marked by O/R mappings allows users to modify their ejb3.0 Entity Bean. in the default environment of EJB 3.0, the table name is the class name. The two are the same. The public Java Bean getter method assumes that the attribute value with the same name in the Access Table is used, developers can modify the default definition through various annotations such as @ table and @ column. example:

@ Entity
@ Table (name = "customer ")
@ Secondarytable (name = "cust_detail ",
Pkjoin = @ primarykeyjoincolumn (name = "cust_id "))
Public Class Customer {...}

@ Entity indicates that this is an entity bean. Table indicates the corresponding o/R Mapping master table, while secondarytable indicates the secondary table corresponding to entity,
Continuous APIs, query languages, and O/R Mapping annotations are part of the EJB 3.0 specification.
The persistence API is designed to run independently of the container. You only need a Java SE environment to run the persistence API.

4. Summary

This article describes some new features of the EJB 3.0 specification. EJB 3.0 will be the biggest change in the history of EJB. It fully absorbs some open-source projects, such as the experience of spring and hibernate, and becomes more convenient and practical, reflecting the design goal of simplified development. This article hopes to bring you an impression about EJB 3.0. Currently, the EJB 3.0 specification has entered the proposed final draft stage. Of course, the technical details of this specification may change in the future.

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.