| 場景 | 推薦組件 |
|---|---|
| 簡單邏輯、數據不共享、非業務實體 | Session Bean + JDBC/SQL |
| 多客戶端共享數據、業務實體建模、需事務管理 | Entity Bean (CMP/BMP) |
Entity Bean 代表持久化業務實體,特徵:
EJB 容器維護連接池,組件通過 JNDI 邏輯名獲取:
@Resource(name="jdbc/AccountDB")
private DataSource ds;
Connection con = ds.getConnection(); // 從池獲取
// 業務邏輯...
con.close(); // 歸還池
優勢:組件與具體數據庫解耦,支援跨環境部署。
ejbCreate - 創建實體public String ejbCreate(String id, String first, String last, double bal)
throws CreateException {
if (bal < 0) throw new CreateException("餘額不能為負");
insertRow(id, first, last, bal); // JDBC INSERT
this.id = id; this.firstName = first; this.lastName = last; this.balance = bal;
return id; // 返回主鍵
}
ejbPostCreate - 創建後續操作對應每個 ejbCreate,通常為空,可調用 getPrimaryKey()。
ejbRemove - 刪除實體public void ejbRemove() {
deleteRow(id); // JDBC DELETE
}
ejbLoad / ejbStore - 同步狀態ejbLoad 從 DB 刷新字段ejbStore 將字段寫回 DBpublic void ejbLoad() { loadRow(); } // SELECT
public void ejbStore() { storeRow(); } // UPDATE
ejbFindByPrimaryKey 返回主鍵ejbFindByLastName、ejbFindInRangeCollection(主鍵集合)ObjectNotFoundException(單一)或 FinderException(集合)public Collection ejbFindByLastName(String name) throws FinderException {
Collection pks = selectByLastName(name); // JDBC SELECT
if (pks.isEmpty()) throw new ObjectNotFoundException("無記錄");
return pks;
}
ejbLoad/store 同步InsufficientBalanceException),系統異常包裝為 EJBExceptionpublic void debit(double amt) throws InsufficientBalanceException {
if (balance - amt < 0) throw new InsufficientBalanceException();
balance -= amt; // 容器稍後自動 ejbStore
}
public interface AccountHome extends EJBHome {
Account create(String id, String first, String last, double bal)
throws RemoteException, CreateException;
Account findByPrimaryKey(String id) throws FinderException, RemoteException;
Collection findByLastName(String last) throws FinderException, RemoteException;
Collection findInRange(double low, double high) throws FinderException, RemoteException;
}
public interface Account extends EJBObject {
void debit(double amt) throws InsufficientBalanceException, RemoteException;
void credit(double amt) throws RemoteException;
String getFirstName() throws RemoteException;
String getLastName() throws RemoteException;
double getBalance() throws RemoteException;
}
AccountHome home = (AccountHome) ctx.lookup("AccountHome");
Account duke = home.create("123", "Duke", "Earl", 0.00);
duke.credit(88.50);
duke.debit(20.25);
System.out.println(duke.getBalance()); // 68.25
EJB 3.0+ 以 JPA (EntityManager + @Entity) 替代 Entity Bean,提供更輕量、標準化的 ORM 方案,建議新項目直接使用 JPA。