EJB Step by STEP

zhaozj2021-02-11  155

EJB Step by STEP

(Problem Description:

We want to create a EJB Connected with a Oracle Table "Statmachine", Which Have Three Fields: ID-VARCHAR2, Quantity-Number, Resdate-Date. The Output File Name of the EJB IS statmachine.jar)

1. Preparing a project for developing the ejb sample [Note: Especially give the attention of the Oracle database driver configuration: (1) Configure the oracle library in JBuilder; (2) Configure the Database drivers in the "Enterprise setup" in JBuilder. 】 2. New - Enterprise - EJB Module, Choose The Proper Setting for Output Jar File, And Give The Proper Jar File Name, That Is Statmachine.jar. 3. Add DataSource. Uses "Import Schema from Database", in The "driver" box, you could choose "oracle.jdbc.driver.OracleDriver" Caution:. the prerequistion of that is you have config your oracle jdbc driver properly (How to do that, please refer to the above I just written).. in the "URL" field, change the "hostname" and "ORCL" to the right setting of your development (hostname refer to the IP of your data server, and ORCL refer the uid of the oracle server that you create in your local client ONE EXAMPLE IS: JDBC: Oracle: Thin: @ 172.16.3.100: 1521: Dev3. At Last, You Can "Refresh From The Database", All the table in your database server will display properly 4. In the design environment of EJB module, create EJB CMP 2.0 entity bean by right click the blank region Setting the proper Bean name;.. "classes and packages .." (for this, only "default package" is required, the others will be setted automatically) Most important:. setting the "table name" field Entity bean setting:. bean name: EbnStatMachine Class-default package: com.ebuilds.erp.pm.ejbs. Entities.cmp.statmachine Table Name: (Add All The Field To Entity Bean As Fields: for Example: ---- ID, Quantity, Resdate) Adds Void SetModel Model Method (

interface: local) increase StatMachineModel getModel () method (interface: local) increase ejbCreate (StatMachineModel model) method (interface: local home) 5. Notes: with ejb pattern, programmer need not use sql statement to update the data table, just leave all the thing to EJB container. and the key point on fullfilling that purpose is the table map between entity bean and database. 6. Add some "field" to entity bean, set the field name and proper type and column name (this name Getting by JB from Database Automatic. Note: for the integer, java.lang.integer is prefer; also java.lang.double is Suitable for Double. 7.ok, Let's Go ON with the session bean. Just Right Click The Design Desktop of EJB Module, Choose Create Session Bean. 8. Just Like Entity Bean, Setting The Right Property of The Session Bean. 9. Add Some Method, Such AS "Insert, Del, QueryBysql, Update ...". All The Method Will be used for the operation of the database directly by The database directly by the outer function of ejb. One Thing Should Be Kept i n mind: change the interfaces setting of the method to remote Setting of session bean: Bean name: SbnStatMachine Session type: stateless interfaces: remote class - default package:. com.ebuilds.erp.pm.ejbs.sessions.stateless.statmachine increase StatMachineModel insert (StatMachineModel model) method (interfaces: remote) to increase StatMachineModel update (StatMachineModel model) method (interfaces: remote) to increase boolean del (String pk) method (interfaces: remote) to increase StatMachineModel findByPk (String pk) method (

Interfaces: remote) Add Boolean Delbatch (Interfaces: Remote) Add Java.util.Collection QueryBysql (String Strsql) 10. Creat A Model File: New - General - Class package: com.ebuilds.erp.pm.javabeans.models.statmachine class name: StatMachineModel [notes: (1) From the hiberarchy of the package, we can see all the models in the "com.ebuilds.erp.pm.javabeans .MODELS "(2) Package Name Should Be The Lowercase; (3) Calss Name Should Be Uppercase In The First Character (4) The meaning of using the Model file here is: All fields in all databases are all in Model, The delivery of data can be used directly without using a single field, which can improve the clarity of data transfer] 11. Change the statmodel.java file intenemodel.java file into the stocking pattern: // begin of the statmodel.java the package of * model .java package com.ebuilds.erp.pm.javabeans.models.statmachine; ************** Module of the * model.java file ********* ************************** Package com.ebuilds.erp.pm.javabeans.models.desktasktotal; import java.io. *; import com.ebuilds.utils.EncodingUTIL; / ** *

Title: Engineering item Plate management system *

Description: *

Copyright: Copyright (c) 2002 *

company: www.ebuilds.net * @Author Anyone * @version 1.0 * com.ebuilds.utils.encodingutil.tobytestring () method * is to process the JSP Chinese encoding conversion problem, it is recommended to use all setxxxx () - * Value object is used in the String type; string getxxxx () Method * Can be used, but if it is not necessary, there is no code quantity, let almost makes excessive make * slow down the program running speed.

- Lee Chi-Ming * / public class DeskTaskTotalModel implements Serializable {private String id; // other direct costs ID private Double quantity; // amount of the fee private java.sql.Date resDate; // date public StatOtherDirectCostModel () {} public String getID ( ) {return this.id;} public void setID (String strId) {this.id = EncodingUtil.toByteString (strId);} public java.sql.Date getResDate () {return resDate;} public void setResDate (java.sql. Date resdate) {this.resdate = resdate;} public Double getquantity () {return quantity;} public void setquantity {this.quantity = quantity;}} / ***************** *********************** Remember to use encodingutil.tobytestring () ****************************** ****************** / // end of statmodel.java ************************************** **************** / * Note: Source code of encodingutil.tobytestring: / ** * String >> char [] >> Byte [] >> String * Solve Chinese issues in JSP * * / public static string TobyTestring (Source == NULL) Return Null; if (Source.length () == 0) Return "" Char [] chars = source.tochararray (); byte [] Bytes = new byte [source.Length () * 2]; int index = 0; for (int i = 0, charvalue = 0; i 255) {Try {byte [] TMP = (New Character (chars [i])). Tostring (). Getbytes "GB2312"); for (int J = 0; j

J ) {bytes [index] = TMP [j]; index ;}} catch (exception e) {E.PrintStackTrace ();}} else {bytes [index] = (byte) Chars [i]; index ;} Return New String (Bytes, 0, Index);} * / 12. Edit The EbnStatmachineBean.java File (this file is generated by jbuilder automatic) (1) .import com.ebuilds.erp.pm.javabeans.models.statmachine .StatMachineModel; (2) Fulfill the "void setModel (StatMachineModel model)" function:. public void setModel (StatMachineModel model) {setId (model.getID ()); setQuantity (model.getQuantity ()); setResDate (model.getResDate ());} (3). Finish the "statmachinemodel getmodel ()" function: public statmodel getmodel () {statmachinemodel data = new statmachinemodel (); data.setId ()); data.setQuantity (THI s.getQuantity ()); data.setResDate (this.getResDate ()); return data;} (4) Finsh the ejbCreate (StatMachineModel) function:. public java.lang.String ejbCreate (StatMachineModel model) throws CreateException {this. SetModel; Return NULL;

} Note for (4): Finishing this ejbCreate function is very important: whenever you call the create () method of the SbnStatMachineHome interface, EJB will automatically call the ejbCreate function] 13. Add two functions for getting the home interface of session bean And Entity Bean: (1.1) Add JNDI Name To The Common Jndi Name Class (com.ebuilds.erp.pm.common.jndinames.java): / **************** ** / public static final String S_STATMACHINE_JDNI = "SbnStatMachine"; public static final String E_STATMACHINE_JDNI = "EbnStatMachine"; [note: (a.) This is the methodology of our company, but not the only way to get the final goal (. b.) The right string of JNDI name of the session bean and the entity bean, such as "SbnStatMachine", could be found by double clicking the navigator tree of the session bean or the entity bean in JBuilder. JNDI name of session bean exists In the field of "home jndi name", and "local home jndi name" for entry bean.】 (1.2) Add GetsbnObjectCostItemh ome () and getEbnObjectCostItemHome () function to the common class (com.ebuilds.erp.pm.common.BaseLookup), a class special for the method getting home interface of seesion bean and entity bean: / ** * acquisition of home SbnStatMachine Interface * @return SbnStatMachineHome * @author Daihua * / protected com.ebuilds.erp.pm.ejbs.sessions.stateless.statmachine.SbnStatMachineHome getSbnStatMachineHome () {com.ebuilds.erp.pm.ejbs.sessions.stateless.statmachine.SbnStatMachineHome Objhome = null; try {javax.naming.context ctx = this.getinitialContext (); //jndinames.s_statmachine_jdni = "sbnstatmachine"

Object ref = ctx.lookup (JNDINames.S_STATMACHINE_JDNI); objHome = (com.ebuilds.erp.pm.ejbs.sessions.stateless.statmachine.SbnStatMachineHome) ref;} catch (Exception e) {e.printStackTrace ();} finally {return objHome;}} / ** * made EbnStatMachine home interface * @return EbnStatMachineHome * @author Daihua * / protected com.ebuilds.erp.pm.ejbs.entities.cmp.statmachine.EbnStatMachineHome getEbnStatMachineHome () {com.ebuilds .erp.pm.ejbs.entities.cmp.statmachine.EbnStatMachineHome objHome = null; try {javax.naming.Context ctx = this.getInitialContext (); //JNDINames.S_STATMACHINE_JDNI = "EbnStatMachine" Object ref = ctx.lookup (JNDINames .E_statmachine_jdni; objhome = (com.ebuilds.mp.pm.ejbs.Entities.cmp.statmachine.ebnstatmachinehome) ref;} catch (exception e) {E.PrintStackTrace ();} finally {returnobjhome;} } [Note: (. A) The above two functions are necessary when you try to invoke entity bean in session bean, using getEbnStatMachineHome (), and when you try to invoke session bean in java bean, using getSbnStatMachineHome ().

(2) The manner above is what our company act as, but in your condition, you could integrate the const and the function into one coincident function 14. Modify the SbnStatMachineBean.java file] [notes:. (. A) all the following functions are designed during the EJB design environment in JBuilder (b.) All the functions will be invoked by java bean, so all are necessary.] (1) import some necessary java classes. (2) Finish the insert () function in SbnStatMachinBean .java file public StatMachineModel insert (StatMachineModel model) {EbnStatMachineHome objHome = this.getEbnStatMachineHome (); try {EbnStatMachine objRemote = objHome.create (model);} catch (Exception e) {e.printStackTrace (); return null;} return MODEL;} (3) Finish the update () function: public statmodel model {ebnstatmachineHome objhome = this.getebnstatmachineHome (); try {ebnstatmachine objRemote = objHome.findByPrimaryKey (model.getID ()); // Call the set serial function to set the model class objRemote.setQuantity (model.getQuantity ()); objRemote.setResDate (model.getResDate ());} catch ( Exception e) {e.printStackTrace (); return null;} return model;} (4) Finish the del () function: public boolean del (String pk) {EbnStatMachineHome objHome = this.getEbnStatMachineHome (); try {EbnStatMachine objRemote = Objhome.FindByPrimaryKey (PK); Objremote.remove ();} catch (exception e) {E.PrintStackTrace (); return false;} return true;

} (5) Finish the findByPk () function: public StatMachineModel findByPk (String pk) {StatMachineModel model = new StatMachineModel (); EbnStatMachineHome objHome = this.getEbnStatMachineHome (); try {EbnStatMachine objRemote = objHome.findByPrimaryKey (pk); model = Objremote.getModel ();} catch (Exception E) {E.PrintStackTrace (); return null;} Return model;} (6) Finish the delbatch () Function: public boolean Delpatch (STRING [] SID) {String [] SID = NULL; SID = SID; STRING SQL = "Delete from stat Machine where id = '"; // NOTE: statMachine is the table name connecture with our work string id = new string (); java.sql.connection conn = null Java.sql.Statement St = NULL; Boolean B = false; try {com.ebuilds.utils.connectionmgr connmgr = new com.ebuilds.utils.connectionmgr (); conn = connmgr.getConnection () Conn.setautocommit (false); st = conn.createstatement (); for (int i = 1; i <= SID.LENGTH; i ) {id = SID [i-1]; st.execute (SQL ID "'");} Conn.commit (); b = true;} catch (exception e) {Try {conn.rollback ();} catch (java.sql.sqlexception SQLE) {} E.PrintStackTrace (); b = false;} finally {Try {st.close ();} catch (exception e) {} try {conn.close ();

} Catch (Exception e) {} return b;}} (7) Finish the queryBySql () function: public java.util.Collection queryBySql (String strSql) {java.util.ArrayList arrayList = null; StatMachineModel item; java.sql .Connection conn = null; java.sql.Statement st = null; java.sql.ResultSet rs = null; try {com.ebuilds.utils.ConnectionMgr connMgr = new com.ebuilds.utils.ConnectionMgr (); conn = connMgr. getConnection (); st = conn.createStatement (); rs = st.executeQuery ( "SELECT * FROM STATMACHINE WHERE" strSql); // Of course, you can change the sql statement according your condition arrayList = new java.util. ArrayList (); while (rs.next ()) {item = new statyinemodel (); item.setId (rs.getstring ("id")); item.setquantity (new double (rs.getdouble)) ); Item.setresdate (RS.Getdate " ")")); Arraylist.add (item);}} catch (java.sql.sqlexception e) {E.PrintStackTrace (); arraylist = null;} catch (Exception E1) {E1.PrintStackTrace (); arraylist = null } Finally {try {if (rs! = Null)}} catch (exception e) {} try {if (st! = Null) st.close ();} catch (exception e) {} Try {if (conn! = null) conn.close ();

} Catch (Exception e) {} return arrayList;}} 15. Now, let's program the java bean: StatMachineAction.java, which will be resposible for the action connected the EJB and the .jsp file (1) create a java class file StatMachineAction.java, which belong the package: com.ebuilds.erp.pm.javabeans.actions.statmachine (2) Following the next code template: ********* Begin of the source code of StatMachineAction.java * ************************************************************** Package COM.EBUILDS.ERP. pm.javabeans.actions.statmachine; import com.ebuilds.erp.pm.javabeans.models.statmachine.StatMachineModel; import java.util.Collection; import com.ebuilds.erp.pm.ejbs.sessions.stateless.statmachine *. Import com.ebuilds.erp.pm.Ejbs.entities.cmp.statmachine. *; import com.ebuilds.utils.debug; / ** *

Title: *

description: *

Copyright: Copyright (c) 2003 *

Company: * @Author unascribed * @version 1.0 * / public class statmachineaction extends com.ebuilds. erp.pm.common.BaseLookup implements com.ebuilds.erp.pm.interfaces.IDocument {public StatMachineAction () {} / ** @param obj @return Object @roseuid 3D76B4E50318 * / public Object add (Object obj) {StatMachineModel data = (Statmachinemodel) Obj; data.setid (com.ebuilds.utils.setcmanager.instance (). GetUnitecode ()); // getUnitecode () The role is to get a unique ID number.

You can write this function, such as using the current time as ID: gettime (); or use the network card physical address plus the current time as ID, etc. System.out.Println ("****** statmachneaction.java debug Information: " " Get UID = " Data.GetId () " ****** "); try {sbnstatmachinehome objhome = this.getsbnstatotherDirectCosthome (); //system.out.println (" *** *** statmachineAction.java debug information: " " There is no mistake here " " ****** "); sbnstatmachine objremote = objhome.create (); return objremote.insert (data);} catch (Exception E ) {//System.out.println("cann't add the SbnStatMachine at SbnStatMachineAction add: " e); e.printStackTrace (); return null;}} / ** @param objPkr @return boolean @roseuid 3D76B4E503B9 * / Public boolean delete (Object objpk) {boolean b = false; try {sbnstatmachinehome objhome = this.getsbnstatmachineHHome (); sbnstatmachine objremote = objhome.create (); b = Obj Remote.del ((String) Objpk;} catch (Exception E) {//system.out.println ("cann't add the sbnstatmachineaction at statyineaction delete:" e); E.PrintStackTrace ();} finally { Return B;}} / ** @Param obj @Return Boolean @Roseuid 3D76B4E60099 * / Public Object Update (Object obj) {Try {//debug.logonelinetofile ("statmachineaction.java", "Update ()", "Start Update Method "); sbnstatmachinehome objhome = this.getsbnstatmachineHome ();

SbnStatMachine objRemote = objHome.create (); //Debug.logOneLineToFile ( "StatMachineAction.java", "update ()", "Begin call SbnStatMachineBean update method"); return objRemote.update ((StatMachineModel) obj);} Catch (Exception E) {//debug.logonelinetofile ("statmachineaction.java", "update ()", "Update method error:" E.getMessage ()); //system.out.println( add the SbnStatMachineAction at StatMachineAction update: " e); e.printStackTrace (); return null;}} / ** @return Object @roseuid 3D76B4E60157 * / public Object findByPk (Object pk) {try {SbnStatMachineHome objHome = this.getSbnStatMachineHome (); SbnStatMachine objRemote = objHome.create (); return objRemote.findByPk (String.valueOf (pk));} catch (Exception e) {//System.out.println("cann't add the SbnStatMachineAction at StatMachineAction findByPk : " E); E.pr intStackTrace (); return null;}} / ** @param sql @return java.util.Collection @roseuid 3D76B4E601A7 * / public Collection queryBySql (String sql) {Collection col = null; try {SbnStatMachineHome objHome = this.getSbnStatMachineHome () ; SbnStatMachine objRemote = objHome.create (); col = objRemote.queryBySql (sql);} catch (Exception e) {//System.out.println("cann't add the SbnStatMachineAction at StatMachineAction queryBySql: " e);

e.printStackTrace ();} finally {return col;}} public boolean deletePatch (String [] sId) {boolean b = false; try {SbnStatMachineHome objHome = this.getSbnStatMachineHome (); SbnStatMachine objRemote = objHome.create (); b = Objremote.delbatch (SID);} catch (Exception E) {//system.out.println ("Cann't Delete Patch At Statmachine DletePatch:" E); E.PrintStackTrace ();} finally {return b; }} public static void main (String [] args) {StatMachineAction action = new StatMachineAction (); StatMachineModel data = new StatMachineModel (); data.setID (com.ebuilds.utils.SecManager.instance () getUniteCode ().); Data.seTamount (New Double (12.34)); // Notes: Follow the actual situation of your EJB Data.SetDescription ("Description1"); Data.SetObjectcostItemid ("Erppm2002121900000000000069352 009027F64EB3 "); data.setPeriodID (" ERPPM20021216000000067508009027F64EB2 "); data.setProjectID (" ERPPM200212110000000658310000E8E7FF69 "); data.setProjResourceID (" A000201 "); data.setWorkID (" ERPPM20021210000000065313009027F64EB2 "); StatMachineModel tempModel = null; java.util.ArrayList Tempal = null; string tempstr = null; / * Verify the add function for (int i = 0; i <6; i ) {data.setid (com.ebuilds.utils.setid (). GetUnitecode ()); action .add (data);

} // * / / * Verify that the DELETE function // runs 5 records in the database Action.delete ("ERPPM2003050700000009834300D04CB077B8"); // * / / * Verify that the deletepatch function // There are 10 records in the database in the database) String) String [] sid = { "ERPPM2003050700000009833500D04CB077B8", "ERPPM2003050700000009833700D04CB077B8", "ERPPM2003050700000009833900D04CB077B8"}; action.deletePatch (sid); // * / / * function verification findByPk tempModel = (StatMachineModel) action.findByPk ( "ERPPM2003050700000009834700D04CB077B8"); System. Out.println ("Get the IDEL ID:" TempModel.GetId ()); System.out.Println ("Take Model Description is" TempModel.getDescription ()); // * / / * Verify QueryBysql functions tempModel = null; String strSql = "PERIODID = 'ERPPM20021216000000067508009027F64EB2'"; tempAl = (java.util.ArrayList) action.queryBySql (strSql); for (int i = 0; i

Action.Update (TempModel); // * /}} [main () function is used to test EJB, as long as you open each annotation (currently, the string should be set correctly according to the content of the database)] **** ***** End of the Source Code of StatmachineAction.Java *************************************** ******** 16. How to debug ejb: (1) prerequistion: configuring the server setting of jbuilder; make sure you have started weblogic prot (; (2) Note: Every time you change the source code of ejb, no matter session bean or entity bean, you need redeploy EJB. (3) Just set a runtime configuration, whose main class is StatMachineAction.java. (4) OK, every is ready, just run that configuration. If you debug the add function , all the data you add should be found in database (5) If some unconsidering problem occur, in most conditions, compiling all the classes connected with the EJB and redeploying the EJB to weblogic will solve the problem 17. The End:.. How To use ejb in .jsp file: statmachineaction theAction = new statmachinection (); // Construct a action Class Statmaachinemodel T empModel = (StatMachineModel) theAction.findByPk (request.getParameter ( "id")); // get the model by action class String strID = tempModel.getID ();. java.lang.Double dQuantity = tempModel.getQuantity (); OK, Tha's all! 18.some Questions ask by myself When I study ejb at the beginning: (1) Q: Is there an entity bean, but also model? A:! Yes model class is used for the data transfer between action and jsp, which is very necessary One model class encapsulate one table in databse, which will make the accessing of the data become very convenient (2) Q:.. With SESSION bean, is also an action bean?

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

New Post(0)