EJB step by step

类别:Java 点击:0 评论:0 推荐:
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. Use "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)
增加void setModel ( StatMachineModel model ) 方法(interface:local)
增加StatMachineModel getModel () 方法 (interface :local )
增加ejbCreate( StatMachineModel model ) 方法 (interface :local home )

5. Notes: with ejb pattern, programmer needn't 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 automatically). 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 outer function of ejb. One thing should be kept in 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
增加 StatMachineModel insert ( StatMachineModel model ) 方法 (interfaces: remote )
增加 StatMachineModel update ( StatMachineModel model ) 方法 (interfaces: remote )
增加 boolean del ( String pk ) 方法 ( interfaces: remote )
增加 StatMachineModel findByPk ( String pk ) 方法 ( interfaces: remote )
增加 boolean delBatch ( String[] sid ) 方法 ( interfaces:remote )
增加 java.util.Collection queryBySql ( String strSql ) 方法 ( interfaces:remote )

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)这里使用model文件的含义是:所有的数据库中的字段全部包装在model中,以后对于数据的传递可以直接使用model,而不用使用单个的字段,这样可以提高数据传递的清晰性】

11. Change the StatMachineModel.java file into the following pattern:
//Begin of the StatMachineModel.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;

/**
* <p>Title: 工程项目管理系统</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: www.ebuilds.net</p>
* @author anyone
* @version 1.0
* com.ebuilds.utils.EncodingUtil.toByteString()方法
* 是处理JSP中文编码转换问题的,建议在所有的setXxxx()-赋
* 值对象是String类型-方法中使用;String getXxxx()方法
* 可以考虑使用,但如无必要,无谓增加代码量,更何况过多的使
* 用会减慢程序运行速度。 --李炽明
*/


public class DeskTaskTotalModel implements Serializable
{
    private String id; //其他直接费用ID
    private Double quantity; //费用金额
    private java.sql.Date resDate; //日期


    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 ( Double quantity ){
        this.quantity = quantity;
    }

}

/************************************
记得使用EncodingUtil.toByteString()呀
************************************/
//End of StatMachineModel.java****************************************
/*Note: <font color=red>Source code of EncodingUtil.toByteString:</font>
    /**
    * String >> char[] >> byte[] >> String
    * 解决JSP中的中文问题
    * */
    public static String toByteString(String source){
        if (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<chars.length&&index<chars.length*2;i++){
            charValue=(int)chars[i];
            if (charValue>255){
                try{
                    byte[] tmp=(new Character(chars[i])).toString().getBytes("GB2312");
                    for (int j=0;j < tmp.length;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 automatically )
(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 StatMachineModel getModel() {
        StatMachineModel data = new StatMachineModel();
        data.setID( this.getId());
        data.setQuantity( this.getQuantity());
        data.setResDate( this.getResDate());
        return data;
    }

(4). Finsh the ejbCreate ( StatMachineModel ) function:
    public java.lang.String ejbCreate(StatMachineModel model) throws CreateException {
        this.setModel( model );
        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):
    /********** StatMachine ********/
    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 entity bean.】
(1.2) add getSbnObjectCostItemHome() 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:
    /**
     * 取得SbnStatMachine的home接口
     * @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;
        }
    }
    /**
     * 取得EbnStatMachine的home接口
     * @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.erp.pm.ejbs.entities.cmp.statmachine.EbnStatMachineHome)ref;
        }catch(Exception e) {
            e.printStackTrace();
        } finally {
            return objHome;
        }
    }

【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 StatMachineModel update(StatMachineModel 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 STATMACHINE WHERE ID='" ; //Note: statmachine is the table name connected 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 StatMachineModel();
                item.setID( rs.getString( "ID" ));
                item.setQuantity( new Double(rs.getDouble("QUANTITY") ) );
                item.setResDate( rs.getDate( "RESDATE" ) );
                arrayList.add(item);
            }
        }catch(java.sql.SQLException e){
            e.printStackTrace();
            arrayList = null;
        }catch(Exception e1){
            e1.printStackTrace();
            arrayList = null;
        }finally{
            try {
                if (rs!=null)
                    rs.close();
            }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;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @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.SecManager.instance().getUniteCode()); //getUniteCode()的作用是:得到一个唯一的ID号。可以随便怎么写这个函数,比如可以用当前的时间作为ID:getTime();或者用网卡物理地址加上当前时间作为ID等等
        System.out.println ( "******StatMachineAction.java Debug information: " + "得到的uid=" + data.getID() + "******");
        try {
            SbnStatMachineHome objHome = this.getSbnStatOtherDirectCostHome();
            //System.out.println ( "******StatMachineAction.java Debug information: " + "这里以上没有错" + "******");
            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.getSbnStatMachineHome();
            SbnStatMachine objRemote = objHome.create();
            b = objRemote.del((String)objPk) ;
        }catch(Exception e){
            //System.out.println("cann't add the SbnStatMachineAction at StatMachineAction delete:" + e);
            e.printStackTrace();
        }finally{
            return b;
        }
    }

    /**
    @param obj
    @return boolean
    @roseuid 3D76B4E60099
    */
    public Object update(Object obj)
    {
        try {
            //Debug.logOneLineToFile( "StatMachineAction.java", "update()", "开始update方法" );
            SbnStatMachineHome objHome = this.getSbnStatMachineHome();
            SbnStatMachine objRemote = objHome.create();
            //Debug.logOneLineToFile( "StatMachineAction.java", "update()", "开始准备调用SbnStatMachineBean的update方法" );
            return objRemote.update((StatMachineModel) obj);
        }catch(Exception e){
            //Debug.logOneLineToFile( "StatMachineAction.java", "update()", "update方法出错:" + e.getMessage() );
            //System.out.println("cann't 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.printStackTrace();
            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 StatMachineAction deletePatch:" + 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: <font color=orange>这里按照你的ejb的实际情况改动</font>
        data.setDescription( "Description1" );
        data.setObjectCostItemID( "ERPPM20021219000000069352009027F64EB3" );
        data.setPeriodID( "ERPPM20021216000000067508009027F64EB2" );
        data.setProjectID( "ERPPM200212110000000658310000E8E7FF69" );
        data.setProjResourceID( "A000201" );
        data.setWorkID( "ERPPM20021210000000065313009027F64EB2" );

        StatMachineModel tempModel = null;
        java.util.ArrayList tempAl = null;
        String tempStr = null ;
        /*验证add函数
        for ( int i = 0; i < 6; i++ )
        {
            data.setID(com.ebuilds.utils.SecManager.instance().getUniteCode());
            action.add( data );
        }//*/

        /*验证delete函数
        //运行前数据库里面有5条记录
        action.delete( "ERPPM2003050700000009834300D04CB077B8" );
        //*/

        /*验证deletePatch函数
        //运行前数据库里面有10条记录)
        String[] sid = { "ERPPM2003050700000009833500D04CB077B8", "ERPPM2003050700000009833700D04CB077B8", "ERPPM2003050700000009833900D04CB077B8" };
        action.deletePatch( sid );
        //*/

        /*验证findByPk函数
        tempModel = (StatMachineModel)action.findByPk( "ERPPM2003050700000009834700D04CB077B8" );
        System.out.println( "取得model的ID是:" + tempModel.getID() );
        System.out.println("取得model的Description是" + tempModel.getDescription() );
        //*/

        /*验证queryBySql函数
        tempModel = null;
        String strSql = "PERIODID = 'ERPPM20021216000000067508009027F64EB2'";
        tempAl = ( java.util.ArrayList ) action.queryBySql( strSql );
        for ( int i = 0; i < tempAl.size(); i ++ )
        {
            tempModel = ( StatMachineModel ) tempAl.get( i );
            System.out.println("取得第" + (i+1) + "个符合条件的记录:");
            System.out.println("\tID=" + tempModel.getID() );
            System.out.println("\tDescription=" + tempModel.getDescription() );
        }//*/

        /*验证update函数
        tempModel = null;
        tempStr = "ERPPM2003050700000009834900D04CB077B8";
        tempModel = (StatMachineModel)action.findByPk( tempStr );
        tempModel.setDescription( "new description" );
        tempModel.setAmount( new Double(44444.44) );
        action.update( tempModel);
        //*/


    }
}


main()函数用来测试EJB,只要依次打开各个注释就可以了(当前,字符串要根据数据库的内容设定正确)


*********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 properly;
(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 StatMachineAction(); //construct a action class
    StatMachineModel tempModel = (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 asked by myself when I study EJB at the beginning:
(1)Q: 有了实体bean,还要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: 有了session bean,还要action bean 吗?
A: Yes! .jsp file should not contact with session bean directly, So, action bean is prefer for the accessing of EJB.
(3) In one word: .jsp file should only communicate with java bean, but not with the EJB.

本文地址:http://com.8s8s.com/it/it17846.htm