accountbean.java
来自「weblogic应用全实例」· Java 代码 · 共 439 行
JAVA
439 行
//定义本类在包examples.ejb20.homeMethods 中
package examples.ejb20.homeMethods;
//本接口用到的其他类
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.NoSuchEntityException;
import javax.ejb.ObjectNotFoundException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
* AccountBean是实体EJB,它演示了:
* 容器管理的JDBC持续性管理和事务管理;
* 在这个文件中的代码并没有直接访问数据库;
* 用户定义的异常;
* 使用isModified方法,这个方法改变容器管理的字段,通过设置isDirty
*/
//这个类是实体Bean,必须实现接口 EntityBean
public class AccountBean implements EntityBean {
//设置是否打印控制台
final static private boolean VERBOSE = true;
//声明实体上下文变量
private EntityContext ctx;
//声明实体EJB属性变量
private String accountId; //主键
private double balance;
/**
* 为EJBean设置实体EJB上下文
*
* @参数 ctx EntityContext
*/
public void setEntityContext(EntityContext ctx) {
log("setEntityContext called");
this.ctx = ctx;
}
/**
* 取消实体上下文设置
*
*/
public void unsetEntityContext() {
log("unsetEntityContext (" + id() + ")");
this.ctx = null;
}
/**
* 这是本类必须实现的方法,在本例中没有用到
*
*/
public void ejbActivate() {
log("ejbActivate (" + id() + ")");
}
/**
* 这是本类必须实现的方法,在本例中没有用到
*
*/
public void ejbPassivate() {
log("ejbPassivate (" + id() + ")");
}
/**
* 从数据库中加载EJBean
*
* @异常 javax.ejb.NoSuchEntityException
* if the bean is not found in the database
* @异常 javax.ejb.EJBException
* if there is a communications or systems failure
*/
public void ejbLoad() {
log("ejbLoad: (" + id() + ")");
//声明数据库连接
Connection con = null;
PreparedStatement ps = null;
accountId = (String) ctx.getPrimaryKey();
try {
//建立数据库连接
con = getConnection();
//执行SQL语句
ps = con.prepareStatement("select bal from ejbAccounts where id = ?");
ps.setString(1, accountId);
ps.executeQuery();
//获取结果集
ResultSet rs = ps.getResultSet();
if (rs.next()) {
balance = rs.getDouble(1);
} else {
String error = "ejbLoad: AccountBean (" + accountId + ") not found";
log(error);
throw new NoSuchEntityException (error);
}
} catch (SQLException sqe) {
//异常处理
log("SQLException: " + sqe);
throw new EJBException(sqe);
} finally {
//清除对象
cleanup(con, ps);
}
}
/**
* 保存EJBean到数据库
*
* @异常 javax.ejb.NoSuchEntityException
* if the bean is not found in the database
* @异常 javax.ejb.EJBException
* if there is a communications or systems failure
*/
public void ejbStore() {
log("ejbStore (" + id() + ")");
//声明数据库连接
Connection con = null;
PreparedStatement ps = null;
try {
//建立数据库连接
con = getConnection();
//执行SQL语句
ps = con.prepareStatement("update ejbAccounts set bal = ? where id = ?");
ps.setDouble(1, balance);
ps.setString(2, accountId);
if (!(ps.executeUpdate() > 0)) {
String error = "ejbStore: AccountBean (" + accountId + ") not updated";
log(error);
throw new NoSuchEntityException (error);
}
} catch(SQLException sqe) {
//异常处理
log("SQLException: " + sqe);
throw new EJBException (sqe);
} finally {
//清除对象
cleanup(con, ps);
}
}
/**
* 这个方法和"AccountBean.java"中定义的的Bean的"ejbCreate"方法相对应
* 这两个方法的参数应该相同。当客户端调用"TraderHome.create()"方法时,EJB容器
* 会找到EJBean的实例,并调用它的"ejbCreate()"方法。
* 对容器管理的ejb,ejbCreate方法返回为null,而bean管理的ejb,返回的是主键类。
* @参数 accountID String 账号ID
* @参数 initialBalance double 初始化结算值
* @异常 javax.ejb.CreateException
* 创建bean错误时抛出的异常
*/
public String ejbCreate(String accountId, double initialBalance)
throws CreateException
{
log("AccountBean.ejbCreate( id = accountId" + ", " + "initial balance = $ " + initialBalance + ")");
this.accountId = accountId;
this.balance = initialBalance;
//以下是数据库操作
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
ps = con.prepareStatement("insert into ejbAccounts (id, bal) values (?, ?)");
ps.setString(1, accountId);
ps.setDouble(2, balance);
if (ps.executeUpdate() != 1) {
String error = "JDBC did not create any row";
log(error);
throw new CreateException (error);
}
return accountId;
} catch (SQLException sqe) {
try {
ejbFindByPrimaryKey(accountId);
} catch(ObjectNotFoundException onfe) {
String error = "SQLException: " + sqe;
log(error);
throw new CreateException (error);
}
String error = "An Account already exists in the database with Primary Key " + accountId;
log(error);
throw new DuplicateKeyException(error);
} finally {
cleanup(con, ps);
}
}
/**
* 这是本类必须实现的方法,在本例中没有用到
*
*/
public void ejbPostCreate(String accountId, double initialBalance) {
log("ejbPostCreate (" + id() + ")");
}
/**
* 从数据库中删除EJBean
*
* @异常 javax.ejb.NoSuchEntityException
* if the bean is not found in the database
* @异常 javax.ejb.EJBException
* if there is a communications or systems failure
*/
public void ejbRemove() {
log("ejbRemove (" + id() + ")");
//以下是数据库操作
Connection con = null;
PreparedStatement ps = null;
try {
//获取连接
con = getConnection();
accountId = (String) ctx.getPrimaryKey();
//执行SQL语句
ps = con.prepareStatement("delete from ejbAccounts where id = ?");
ps.setString(1, accountId);
if (!(ps.executeUpdate() > 0)) {
String error = "AccountBean (" + accountId + " not found";
log(error);
throw new NoSuchEntityException (error);
}
} catch (SQLException sqe) {
//异常处理
log("SQLException: " + sqe);
throw new EJBException (sqe);
} finally {
//清除对象
cleanup(con, ps);
}
}
/**
* 给定主键查找EJB
*
* @参数 pk String 主键
* @返回 String 主键
* @异常 javax.ejb.ObjectNotFoundException
* thrown if the EJBean cannot be found
* @异常 javax.ejb.EJBException
* if there is a communications or systems failure
*/
public String ejbFindByPrimaryKey(String pk)
throws ObjectNotFoundException
{
log("ejbFindByPrimaryKey (" + pk + ")");
//以下是数据库操作
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
ps = con.prepareStatement("select bal from ejbAccounts where id = ?");
ps.setString(1, pk);
ps.executeQuery();
ResultSet rs = ps.getResultSet();
if (rs.next()) {
balance = rs.getDouble(1);
} else {
String error = "ejbFindByPrimaryKey: AccountBean (" + pk + ") not found";
log(error);
throw new ObjectNotFoundException (error);
}
} catch (SQLException sqe) {
log("SQLException: " + sqe);
throw new EJBException (sqe);
} finally {
cleanup(con, ps);
}
log("ejbFindByPrimaryKey (" + pk + ") found");
return pk;
}
/**
* 查找大于给定数量的EJBeans
* 返回EJBean主键的枚举
*
* @参数 balanceGreaterThan double 数量
* @返回 Enumeration EJBean主键的枚举
* @异常 javax.ejb.EJBException
* if there is a communications or systems failure
*/
public Enumeration ejbFindBigAccounts(double balanceGreaterThan) {
log("ejbFindBigAccounts (balance > " + balanceGreaterThan + ")");
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
ps = con.prepareStatement("select id from ejbAccounts where bal > ?");
ps.setDouble(1, balanceGreaterThan);
ps.executeQuery();
ResultSet rs = ps.getResultSet();
Vector v = new Vector();
String pk;
while (rs.next()) {
pk = rs.getString(1);
v.addElement(pk);
}
return v.elements();
} catch (SQLException sqe) {
log("SQLException: " + sqe);
throw new EJBException (sqe);
} finally {
cleanup(con, ps);
}
}
/**
* 存入一定金额
*
* @参数 amount double 数量
* @返回 double 结算
*/
public double deposit(double amount) {
log("Depositing $" + amount + " into '" + accountId + "'");
balance += amount;
return balance;
}
/**
* 提取一定数量的金额
*
* @参数 amount double 数量
* @返回 double 结算
* @exception ProcessingErrorException
* 如果提取的数量大于结算值
*/
public double withdraw(double amount)
throws ProcessingErrorException
{
log("Withdrawing $" + amount + " from '" + accountId + "'");
if (amount > balance) {
String error = "Request to withdraw $" + amount +
" more than balance " + balance + " in account " + accountId;
log(error);
throw new ProcessingErrorException(error);
}
balance -= amount;
return balance;
}
/**
* 返回当前的结算
*
* @返回 double 结算
*/
public double balance() {
return balance;
}
/**
* 从连接池中获取当前的连接
*
* @返回 Connection
* @异常 javax.ejb.EJBException
* if there is a communications or systems failure
*/
private Connection getConnection()
throws SQLException
{
InitialContext initCtx = null;
try {
initCtx = new InitialContext();
DataSource ds = (javax.sql.DataSource)
initCtx.lookup("java:comp/env/jdbc/demoPool");
return ds.getConnection();
} catch(NamingException ne) {
log("UNABLE to get a connection from demoPool!");
log("Please make sure that you have setup the connection pool properly");
throw new EJBException(ne);
} finally {
try {
if(initCtx != null) initCtx.close();
} catch(NamingException ne) {
log("Error closing context: " + ne);
throw new EJBException(ne);
}
}
}
// 也可以考虑使用WebLogic日志服务
private void log(String s) {
if (VERBOSE) System.out.println(s);
}
// 返回这个beans的id
private String id() {
return "PK = " + (String) ctx.getPrimaryKey();
}
//清除对象
private void cleanup(Connection con, PreparedStatement ps) {
try {
///关闭语句对象
if (ps != null) ps.close();
} catch (Exception e) {
//异常处理
log("Error closing PreparedStatement: "+e);
throw new EJBException (e);
}
try {
//关闭连接
if (con != null) con.close();
} catch (Exception e) {
//异常处理
log("Error closing Connection: " + e);
throw new EJBException (e);
}
}
/**
* 这个方法与主接口中的testHomeMethod方法对应
*/
public String ejbHomeHomyMethod() {
String s = "Sample: AccountBean.ejbHomeHomyMethod() invoked";
System.out.println(s);
return s;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?