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

📄 studentbean.java

📁 J2EE开发与Weblogic一书中的源代码
💻 JAVA
字号:
package com.learnweblogic.examples.ch9.bmp;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
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;

// The source files in this book use explicit imports instead of
// importing a package.*.  While this is a matter of personal
// preference, using explicit imports allows the user to quickly scan
// the file and learn which package contains a class.

public class StudentBean 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;

  // The name, ssn, and grade variables are the bean's fields.  They
  // will be initialized in ejbCreate, loaded from the database in
  // ejbLoad, and stored to the database in ejbStore.  The ssn field
  // is the student's social security number and serves as the primary
  // key for this bean.

  private String name;
  private Integer ssn; // primary key
  private int grade;


  // 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;
  }


  // The ejbCreate method will initialize the member variables from the
  // passed parameters and then insert the new entity bean into the
  // database.  If the insert fails, a SQLException will be thrown.
  // The ejbCreate method then uses its ejbFindByPrimaryKey method to
  // determine whether the key already exists in the table.  If the
  // key is already present in the table, ejbFindByPrimaryKey will
  // return successfully, and the ejbCreate method will throw the
  // DuplicateKeyException to inform the caller.  Otherwise, an
  // EJBException is thrown with the SQLException.


  public Integer ejbCreate(String name, int ssn, int grade)
  {

    this.name      = name;
    this.ssn       = new Integer(ssn);
    this.grade     = grade;

    Connection       con = null;
    PreparedStatement ps = null;

    try {

      con = dataSource.getConnection();

      ps = con.prepareStatement("insert into "+tableName+
        " (name, ssn, grade) values (?,?,?)");

      ps.setString(1, name);
      ps.setInt(2, ssn);
      ps.setInt(3, grade);

      ps.executeUpdate();

      return this.ssn;

    } catch (SQLException sqe) {


      try {
        ejbFindByPrimaryKey(this.ssn);

        throw new DuplicateKeyException("A student with social "+
          "security number: "+ssn+" already exists.");
      } catch (Exception Ignore) {}

      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(String name, int ssn, int grade) {}


  // 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 {
      con = dataSource.getConnection();
      ps  = con.prepareStatement("delete from "+tableName+
        " where ssn=?");
      ps.setInt(1, ssn.intValue());

      if (ps.executeUpdate() < 1) {
        throw new RemoveException ("Error removing Student with ssn: "+ssn);
      }
    } 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() {

    ssn = (Integer) ctx.getPrimaryKey();

    Connection con       = null;
    PreparedStatement ps = null;
    ResultSet rs         = null;

    try {
      con = dataSource.getConnection();
      ps  = con.prepareStatement("select name, grade from "
        +tableName+ " where ssn=?");
      ps.setInt(1, ssn.intValue());
      ps.executeQuery();
      rs = ps.getResultSet();

      if (rs.next()) {
        name  = rs.getString(1);
        grade = rs.getInt(2);

      } else {
        throw new NoSuchEntityException("Student with social "+
          "security number: "+ssn+" 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 {
      con = dataSource.getConnection();
      ps  = con.prepareStatement("update "+tableName+
        " SET name=?, grade=? " +
        " where ssn=?");

      ps.setString(1, name);
      ps.setInt(2, grade);
      ps.setInt(3, ssn.intValue());

      ps.executeUpdate();

    } catch (SQLException sqe) {
      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 {
      con = dataSource.getConnection();
      ps  = con.prepareStatement("select ssn from "+tableName+
        " where ssn=?");
      ps.setInt(1, pk.intValue());
      ps.executeQuery();

      rs = ps.getResultSet();

      if (rs.next()) {
        return pk;
      } else {
        throw new ObjectNotFoundException ("Student with social "+
          "security number: "+ssn+" 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 ejbFindStudentsInGrade method returns a Collection of
  // students 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 ejbFindStudentsInGrade(int gradeValue) {

    Connection con       = null;
    PreparedStatement ps = null;
    ResultSet rs         = null;

    ArrayList keys = new ArrayList();

    try {
      con = dataSource.getConnection();
      ps  = con.prepareStatement("select ssn from "+tableName+
        " where grade=?");
      ps.setInt(1, gradeValue);
      ps.executeQuery();

      rs = ps.getResultSet();

      while (rs.next()) {
        keys.add(new Integer(rs.getInt(1)));
      }

      return keys;

    } 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) {}
    }


  }


  // These methods implement the business methods defined in the
  // Student Remote interface.

  public String getName() { return name; }

  public Integer getSsn() { return ssn; }

  public int getGrade() { return grade; }

  public void setGrade(int grade) { this.grade = grade; }


}


⌨️ 快捷键说明

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