The following is a simple example "Bank Account" application system to introduce 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 work: • Insert the status of the Entity bean to the database? Initialize the instance variable? 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;}