⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bankbean.java

📁 java的一系列产品中包括jsme,jmse,j2ee,本文件提供j2ee实现的源代码.
💻 JAVA
字号:
package bankbmp;

// The source files use explicit imports instead of importing a package.*.
// While this is a matter of personal preference, using explicit imports 
// allows the user to quickly learn which package contains a class.
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javax.ejb.DuplicateKeyException;
import javax.ejb.EntityContext;
import javax.ejb.EntityBean;
import javax.ejb.EJBException;
import javax.ejb.NoSuchEntityException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class BankBean implements EntityBean {

  // The next three variables are instance variables, but are not tied
  // to a particular identity/primary key.  These variables are set in
  // the setEntityContext method before the bean has an identity and
  // are used for the lifetime of the bean instance.

  private EntityContext ctx;
  private DataSource dataSource;
  private String tableName;

  private Integer accountID; //primary key
  private String ownerName;
  private float accountValue;  
  private int accountLevel;


  // The setEntityContext method receives an EntityContext reference
  // which it stores in a member variable.  It also uses the EJB's
  // environment context to look up some deployment-specific
  // parameters.  When the EJB is deployed, the deployer will specify
  // values for the tableName and poolName parameters in the
  // ejb-jar.xml which match the deployment environment.  This allows
  // these values not to be hard-coded into the bean.  The
  // setEntityContext method also gets a DataSource object from the
  // environment.  This will be used to get database connections from
  // the connection pool.

  public void setEntityContext(EntityContext c) {

    ctx = c;

    try {
      Context envCtx = (Context) new InitialContext().lookup("java:/comp/env");

      tableName = (String) envCtx.lookup("tableName");
      
      String poolName = (String) envCtx.lookup("poolName");

      dataSource = (DataSource) envCtx.lookup("/jdbc/"+poolName);
    } catch (NamingException ne) {
      // EJB was not deployed properly
      throw new EJBException(ne);
    }

  }

  public void unsetEntityContext() {
    ctx = null;
  }

  public Integer ejbCreate(int accountID,String ownerName,
  									       float accountValue,int accountLevel)
  {
    this.accountID      = new Integer(accountID);
    this.ownerName      = ownerName;
    this.accountValue   =accountValue;
    this.accountLevel   = accountLevel;

    Connection       con = null;
    PreparedStatement ps = null;
    Statement stmt=null;

    try {
      con = dataSource.getConnection();
			System.out.println("----\nConnect successful");
      ps = con.prepareStatement("insert into "+tableName+
        " (accountID,ownerName,accountValue,accountLevel) values(?,?,?,?)");
      ps.setInt(1,accountID);
      ps.setString(2,ownerName);
      ps.setFloat(3,accountValue);
      ps.setInt(4,accountLevel);
      ps.executeUpdate();
      System.out.println(accountID+"  "+ownerName);
      System.out.println(accountValue+"  "+accountLevel);
      System.out.println("insert successful:"+tableName);
      //when use no-transaction sataSource add follow:
      //con.commit();
      return this.accountID;
    } catch (SQLException sqe){
      try {
        ejbFindByPrimaryKey(this.accountID);
        throw new DuplicateKeyException("A Bank with bank "+
                 "account: "+accountID+" already exists.");
      } catch (Exception Ignore){}
      	System.out.println("Insert failed");
      	//sqe.printStackTrace();
      	throw new EJBException(sqe);
    } finally {
      try {
        if (ps != null) ps.close();
        if (con != null) con.close();
      } catch (Exception ignore) {}
    }
  }

  // This implementation requires no post-create initialization so
  // this required method is empty
  public void ejbPostCreate(int accountID,String ownerName,
  									       float accountValue,int accountLevel) {}

  // The ejbRemove method is responsible for deleting the instance
  // from the database.  This method uses a SQL delete to delete the instance.
  public void ejbRemove() throws RemoveException
  {
    Connection con = null;
    PreparedStatement ps = null;
    try {
    	System.out.println("ejbRemove()");
      con = dataSource.getConnection();
      ps  = con.prepareStatement("delete from "+tableName+
        " where accountID=?");
      ps.setInt(1, accountID.intValue());
      if (ps.executeUpdate() < 1) {
        throw new RemoveException ("Error removing Bank with accountID: "+accountID);
      }
    } catch (SQLException sqe) {
      throw new EJBException (sqe);
    } finally{
      try {
        if(ps != null) ps.close();
        if(con != null) con.close();
      } catch (Exception ignore) {}
    }
  }

  // ejbLoad reads the entity bean's current state from the database
  // and assigns the values to its member variables.  The primary key
  // is available from the EntityContext member variable.  If the
  // entity bean no longer exists, NoSuchEntityException is thrown.
  // This might occur if the entity bean was deleted by another client
  // or directly from the database.
  public void ejbLoad() {
    accountID = (Integer) ctx.getPrimaryKey();
    Connection con       = null;
    PreparedStatement ps = null;
    ResultSet rs         = null;
    try {
    	System.out.println("ejbLoad()");
      con = dataSource.getConnection();
      ps  = con.prepareStatement("select ownerName,accountValue,accountLevel from "+
            tableName+ " where accountID=?");
      ps.setInt(1, accountID.intValue());
      ps.executeQuery();
      rs = ps.getResultSet();

      if (rs.next()) {
      	ownerName = rs.getString(1);
        accountValue  = rs.getFloat(2);
        accountLevel = rs.getInt(3);
      } else {
        throw new NoSuchEntityException("Bank with bank "+
          "account: "+accountID+" no longer exists.");
      }
    } catch (SQLException sqe) {
      throw new EJBException(sqe);
    } finally {
      try {
        if (rs != null) rs.close();
        if (ps != null) ps.close();
        if (con != null) con.close();
      } catch (Exception ignore) {}
    }
  }

  // The ejbStore method will be called to write the entity bean's
  // state back to the database.  The primary key field is not written
  // since primary keys should never change.  An optimized version of
  // this bean could also skip writing the name field since it is
  // never updated.
  public void ejbStore(){
    Connection con       = null;
    PreparedStatement ps = null;
    try {
    	System.out.println("ejbStore()");
      con = dataSource.getConnection();
      ps  = con.prepareStatement("update "+tableName+
        " SET ownerName=?,accountValue=?,accountLevel=? where accountID=?");

      ps.setString(1, ownerName);
      ps.setFloat(2, accountValue);
      ps.setInt(3, accountLevel);
      ps.setInt(4, accountID.intValue());
      
      ps.executeUpdate();
    } catch (SQLException sqe) {
      System.out.println("ejbStore() error");
      //throw new EJBException(sqe);
    } finally {
      try {
        if (ps != null) ps.close();
        if (con != null) con.close();
      } catch (Exception ignore) {}
    }
  }

  // The ejbActivate and ejbPassivate methods are required by the
  // EntityBean interface, but this bean does not use these callbacks.
  public void ejbActivate() {}
  public void ejbPassivate() {}
  
  // The ejbFindByPrimaryKey method needs to test whether the passed
  // key exists in the database.  If the select returns a row then the
  // primary key is returned.  If the key does not exist, an
  // ObjectNotFoundException is thrown.
  public Integer ejbFindByPrimaryKey(Integer pk) 
    throws ObjectNotFoundException
  {
    Connection con       = null;
    PreparedStatement ps = null;
    ResultSet rs         = null;
    try {
    	System.out.println("ejbFindByPrimaryKey()");
      con = dataSource.getConnection();
      ps  = con.prepareStatement("select accountID from "+tableName+
        " where accountID=?");
      ps.setInt(1, pk.intValue());
      ps.executeQuery();

      rs = ps.getResultSet();

      if (rs.next()) {
        return pk;
      } else {
        throw new ObjectNotFoundException ("Bank with bank "+
          "account: "+accountID+" no longer exists.");
      }
    } catch (SQLException sqe) {
      //throw new EJBException (sqe);
      throw new EJBException("ejbFindByPrimaryKey() error");
    } finally {
      try {
        if(rs != null) rs.close();
        if(ps != null) ps.close();
        if(con != null) con.close();
      } catch (Exception ignore) {}
    }
  }
  // The ejbFindBankLevel method returns a Collection of
  // Banks which match the query.  The finder method returns a
  // Collection of primary keys.  The EJB container will convert these
  // into EJBObject references and return them to the client.  If now
  // primary keys match the query, an empty Collection is returned.
  public Collection ejbFindBankLevel(int accountLevelValue) {
    Connection con       = null;
    PreparedStatement ps = null;
    ResultSet rs         = null;

    ArrayList keys = new ArrayList();
    try {
      con = dataSource.getConnection();
      ps  = con.prepareStatement("select accountID from "+tableName+
        " where accountLevel=?");
      ps.setInt(1, accountLevelValue);
      ps.executeQuery();

      rs = ps.getResultSet();
      while (rs.next()) {
        keys.add(new Integer(rs.getInt(1)));
      }
      return keys;
    } catch (SQLException sqe) {
      //throw new EJBException (sqe);
      throw new EJBException("get PK error"); 
    } finally {
      try {
        if(rs != null) rs.close();
        if(ps != null) ps.close();
        if(con != null) con.close();
      } catch (Exception ignore) {}
    }
  }
  // These methods implement the business methods defined in the
  // Bank Remote interface.
  public String getownerName() { return ownerName; }
  public Integer getaccountID() { return accountID; }
  public int getaccountLevel() { return accountLevel; }
  public void setaccountLevel(int accountLevel) {
  	this.accountLevel = accountLevel;
  }
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -