EJB technology database application

zhaozj2021-02-17  52

Thesis:

This article introduces the introduction of the entry of the EJB database application, which is designed to introduce the main requirements of EJB database applications and database programming. Many new concepts involved, the detailed requirements of EJB component programming and the detailed code of Account EJB components, and integration of Account Components. In detail, the example code of this article is included in Sun's Java 2 Enterprise Edition. Keywords J2EE, EJB technology, database

EJB technology database application

I. J2EE Technical Introduction J2EE is an architecture proposed by Sun's distributed environment. It provides a method based on component-based design, development, integration, deployment enterprise application system, and J2EE platform provides multiple layers of distribution. The application system model, the ability to reuse components, unified security models and flexible transaction control. Component-based J2EE Enterprise Application has platform independence, so as not subject to any software product and any software manufacturer API.

J2EE defines the following components: Application Client and Applets are customer layer components; · Java servlets and JSP components are web layer components; Enterprise JavaBean (EJB) component is a business processing layer component.

EJB technology is part of the J2EE system, and the EJB component is written in Java language, which is a reusable server-side component that can be accessed by the client program. It runs on the J2EE server, in the client / server system, EJB provides similar The service of middleware.

J2EE Server provides application system-level services, like transaction management, security management, data inventory, developers don't have to develop system-level services themselves, so you can concentrate on developing business logic processing in application systems; using EJB components to handle business logic . Second, EJB Components Introduction EJB Components are divided into two categories: Sesson Bean and Entity Bean Sesson bean represent the client of the J2EE server, the client can be used by calling the sesson bean's function and J2EE server communication, Sesson Bean and customer sessions, can be considered client Extensions, for example: customers on online accounts can call the function of "Input Deposit Separation" of the sesson bean to store cash. Each Sesson Bean can only have a customer, and when the customer terminates, the corresponding sesson bean is also terminated. Therefore, the sesson bean is temporary and unbelieving.

Entity Bean represents a business handling object, which is stored in a persistent storage mechanism such as a database, for example, an Entity Bean represents an account depiccation, which is a row that stores a single table in the relational database. The information of the Entity bean is not necessarily stored in the relational database, which can also be stored in the object database, in the file or other stored mechanism (this example is used in this example). Entity Beans can be shared by multiple clients. Since multiple clients may change the same data, Entity Bean is important under transaction management. Normally, the EJB container provides transaction management. Developers can specify the properties of transactions in the deployment description file of the component. Each Entity Bean has a unique object identifier, also called the primary key, which allows the client to locate an Entity Bean. Entity Bean's persistence can be managed by Entity Bean, or allows EJB container management, and Entity Bean management requires developers to provide data access code in the Entity Bean. For example, the customer's Entity Bean wants to call the SQL statement to access the relational database through the JDBC. EJB container management Entity Bean persistence means that the EJB container automatically handles data access. SESSSON bean and Entity beans are compared to: Two types of EJB components (session beans and entity beans) can access databases. Which class EJB component is selected to access a database dependent on a specific application system. The following cases can be called to access the SQL statement in the session bean component to access the database: • The application system is relatively simple. • The data returned by the SQL statement cannot be used by multiple clients. · Data does not represent a business entity. The following is to use the entity beans component: • More than one client uses the database to call the returned data. · The data represents a business entity. · Developers want to hide the relationship model from Sesson Beans.

This flexibility in the EJB structure allows developers to develop application systems in different ways. Third, establish a database connection EJB container maintenance database connection pool, this connection pool is transparent to the EJB component. When the EJB component applies for a connection, the EJB container extracts a connection from the connection pool and assigns it to the component. Since the EJB container is only assigned a connection to the EJB component, the components will quickly get this connection and connect to the database. After the database is called, the component can release the connection so it can be applied quickly to another connection. Also because one component only occupies this connection very short, the same connection can be used by multiple components. Components are not to connect to the database through the absolute name of the database, but use the logical name to the database, that is, using JNDI Lookup to get database connections, for example: In the AccountEJB class in the following example, the connection database has the following steps: 1, Specify the logical name of the database: private string dbname = "java: comp / env / jdbc / accountdb"; , Get a database connection from the data source: Connection Con = ds.getConnection ();

This indirect connection database has the following advantages: • The same EJB component can be deployed in different environments with different database names. · You can reuse EJB components in multiple applications. · You can integrate EJB components to run in applications where you are distributed.

In addition, the EJB specification does not require J2EE implementation to support a particular type of database system, so the EJB component can be connected to a different database system. 4. Example of the EJB database application Next, a simple example "Bank Account" application system describes the component access database of the EJB component's ENTITY BEAN type. Entity Bean Status In the Account Table of the Relational Database, Table Account creates: Create Table Account (ID VARCHAR (3) Constraint PK_ACCOUNT Primary Key, Firstname Varchar (24), Lastname Varchar (24), Balance Decimal (10.2)); Like other EJB components, developers must write Entity Bean's Entity Bean Class code (AccountHome.java) and Remote Interface Code (Account.java).

Entity Bean Class code (Accountejb.java)

ENTITYBEAN Interface Method EJBCREATE Method: When the client calls the CREATE method, the EJB container calls the corresponding EJBCREATE method. EJBCREATE Method for an Entity Component To implement the following: • Inserting the state bean to the database • Initialize instance variables • Return to the primary key.

AccountEJB the ejbCreate method insertRow method is called, and insertRow method issues an insert Entity Bean the insert SQL statements state to the database, the following source code Account class ejbCreate method: sublic String ejbCreate (String id, String firstName, String lastName, double BALANCE) Throw createException {IF (Balance <0.00) {throw new createException ("a NEGATIVE INITIAL BALANCE IS Not ALLOWED.");}

Try {INSERTROW (ID, firstname, lastname, balance);} catch (exception ex) {throw new ejbexception ("ejbcreate:" ex.getMessage ());}

THIS.ID = ID; this.firstname = firstname; this.lance = balance;

Return ID;} The throws clause can include the exception processing routine specified in Javax.ejb.createException and other application systems. The state of the Entity bean can also be inserted directly into the database via a non-J2EE application, such as the SQL language script inserting a row of lines into the Account table, although this data is not inserted into the database via the EJBCREATE method, but Entity Bean can also pass the customer Did the program positioning this data.

ejbPostCreate method for each ejbCreate method, developers must write a ejbPostCreate method Entity Bean in, EJB container after call completion ejbCreate, immediately call ejbPostCreate, and ejbCreate methods are not the same, ejbPostCreate method can be called getPrimaryKey other methods, usually ejbPostCreate method It is empty. EJBREMOVE Method When the client deletes a status data of an Entity BEAN by calling the REMOVE method, the EJB container calls the EJBREMOVE method, and the EJBREMOVE method removes an Entity Bean status data from the database. The code is as follows: public void ejbremove () {try {deleterow (id);} catch (exception ex) {throw new ejbexception ex ("ejbremove:" esgetMessage ());}}

If the EJBRemove method encounters a system-level error, javax.ejb.ejbexception is executed. If you encounter an application level error, Javax.ejb.RemoveException will be performed. The status data of the Entity bean can also delete data directly through the DELETE statement of the database.

EJBLOAD method and EJBSTORE method EJB container needs to maintain the instance variable of Entity Bean and the synchronization of the corresponding value in the database, which requires calling the EJBLAOD method and the EJBStore method. The EJBLOAD method is refreshed with the value of the data in the database, and the EJBStore method writes the value of the variable into the database. The client cannot call the EJBLOAD method and the EJBStore method. If the method of business processing is related to the processing, the EJB container is called to call the EJBLOAD method before the service processing method call, and the EJB container immediately calls the EJBStore method to store the data into the database. Because the EJB container calls the EJBLOAD method and EJBStore method, the developer does not have to refresh and store the value of the instance variable in the business processing method. If the EJBLOAD method and the EJBStore method cannot locate the Entity Bean in the low-level database, Javax.ejb.NosuChentityException will be performed. In the AccountEJB class, the EJBLOAD method calls the LoadRow method. LoadRow issues a SELECT statement assigned to an instance variable from the database extraction data; the EJBStore method calls the StoreRow method, and the StoreRow method stores the value of the instance variable to the database with the Update statement. code show as below:

Public void ejbload () {Try {loadRow ();} catch (exception ex) {throw new ejbexception ("ejbload:" ex.getMessage ());}}

Public void ejbstore () {Try {storerow ();} catch (exception ex) {throw new ejbexception ("EJBStore:" ex.getMessage ());}}

Finder method: Finder method allows clients to find Entity Bean, three methods in AccountClient lookup Entity Bean: Account Jones = Home.FindByPrimaryKey ("836"); Collection c home.findbylastName ("smith"); Collection c home.findinrange 20.00,99.00); Entity bean class must implement the appropriate methods, and the file name to start ejbFind prefix, such as: AccountEJB ejbFindByLastName class method implementation is as follows: public Collection ejbFinfBylastName (String lastName) throw FinderException {Collection result; Try {Result = selectByLastName (lastName);} catch (Exception ex) {throw new EJBException ( "ejbFindByLastName" ex.getMessage ());} if (result.isEmpty ()) {throw new ObjectNotFoundException ( "No row found.");} else {return result;}} finder in particular applications, such as ejbFindByLastName and ejbFindInRange, are optional, but must contain ejbFindByPrimaryKey method, method ejbFindByPrimaryKey primary key as a parameter, is used to locate a data entity bean state, the following method is ejbFindByPrimaryKey Code: Public String EjbfindByprimaryKey (String PrimaryKey) throws FinderException {Boolean Result

Try {result = selectByPrimaryKey (PrimaryKey);} catch (exception ex) {throw new ejbexception ("ejbfindbyprimarykey:" ex.getMessage ();}

IF (result) {returnprn primarykey;} else {throw new ObjectNotFoundException ("ROW for ID" PrimaryKey "NOT Found.");}}

The EJBFindByPrimaryKey method is used as a parameter and returns its value. Note: 1. Only the EJB container can call EJBFindByPrimaryKey, and the client cannot call the EJBFindByPrimaryKey method, and the client can only call the FindByPrimaryKey defined in the Home interface. 2. Developers must implement the EJBFindByPrimaryKey method in the Entity Bean class. 3. The name of a Finder method must be prefixed as EJBFIND. 4. The return value must be a primary key or a collection of primary keys. The Throw clause can include javax.ejb.findeRexception, and other other exception processing routines. If a Finder method only requires returning a unique primary key, if the primary button does not exist, you should execute javax.ejb.ObjectNotFoundException, ObjectNotFoundException is a subclass of FoundException; if the Finder method requires returning a collection of primary keys, you should perform FINDEREXCEPTION. deal with.

The business processing method business processing method contains business processing logic wanting to implement in the Entity Bean. Usually the business processing method does not access the database, which allows developers to independently from data inventory from data inventory. Service processing method comprising the following in the AccountEJB entity bean: public void debit (double amount) throw InsufficientBalanceException {if (balance - amount <0) {throw new InsufficientBalanceException ();} balance - = amount;}

Public void credit (double amount) {balance = amount;}

Public string getfirstname () {return firstname;}

Public string getlastname () {return Lastname;}

Public Double getBalance () {return balance;}

Calling business processing method in AccountClient program: Account duke = home.create ("123", "duke", "erl", 0.00); duke.credit (88.50); ​​dUBE.DEBIT (20.25); double balance = duke.getBalance (); Note: 1, the name of the business processing method cannot be the name conflict of the method defined in the EJB system, and other requirements for other requirements in Entity Beans and other methods in Sesson Beans. 2, you can include an exception processing routine that the application definition in the throw clause, such as the DEBIT method executes InsufficientBalanceException. To identify system-level errors, business processing logic should call javax.ejb.ejbexception.

Below is a summary of accessing a database in an AccountEJB class: Because the database does not need to access the database, the business processing method in the Accountejb class is not available. However, the business processing method can modify the instance variable by calling the EJBStore via the EJB container. Of course, developers can also access databases in an AccountEJB class business processing method, depending on the specific requirements of the application, and must connect to the database before accessing the database. The HOME interface (Interface) defines how to create and find the Entity Bean in the Home interface. Account Home Interface follows: import java.util.Collection; import java.rmi.RemoteException; import javax.ejb *; public interface AccountHome extends EJBHome {public Account create (String id, String firstName, String lastName, double balance) throws RemoteException. , CreateException; Public Account FindByPrimaryKey (String ID) Throws FinderException, RemoteException; Public Collection FindbyLastName (String Lastname) Throws FingeRexception, RemoteException;

Public Collection Findinrange (Double Low, Double High), RemoteException;} In the home interface, each of the Finder method must correspond to the Finder method in the Entity Bean class; the name of the Finder method must start with Find, like Entity Bean The Finder method in the class must be the same as EJBFIND, for example: the FindByLastName method defined in the AccountHome class and the EJBFindBylastName method implemented in the AccountJB class.

The Remote Interface Remote Interface Defines the service processing method that the client can call, the code of the Account Remote interface is as follows:

Import javax.ejb.ejbobject; import java.rmi.RemoteException;

Public Interface Account Extends EjBobject {Public Void Debit (Double Amount) Throws Insufficient, RemoteException; Public Void Credit (Double Amount) Throws RemoteException;

Public string getfirstname () throws remoteexception;

PUBLIC STRING GetLastname () THROWS RemoteException;

Public Double getBalance () throws remoteexception;}

转载请注明原文地址:https://www.9cbs.com/read-30856.html

New Post(0)