Sun Java System Application Server 支援 EJB 1.1、2.0、2.1 版 CMP Bean 的自動主鍵生成。本文說明如何配置與實作。
在 ejb-jar.xml 中將 prim-key-class 設為 java.lang.Object 即可啟用自動主鍵。擁有自動主鍵的 CMP Bean 可參與與其他 CMP Bean 的關聯。注意:不支援資料庫自動生成的主鍵值(如 identity、sequence)。
NUMERIC(19) 或更高精度,且不對應任何 CMP 欄位。執行時由伺服器生成唯一值。CREATE TABLE customer (
id BIGINT(19) NOT NULL auto_increment, -- 由資料庫自動生成
lastName varchar(25) NOT NULL,
firstName varchar(30) default NULL,
PRIMARY KEY (id)
);
CustomerModuleorg.bank、資料表 customerid 識別為主鍵並建立 CMP 欄位與 finder 方法id CMP 欄位(專案視窗 企業 Bean > CustomerEB > CMP 欄位,右鍵刪除)ejbCreate 與 ejbPostCreate:public java.lang.Object ejbCreate(java.lang.String lastName, java.lang.String firstName)
throws javax.ejb.CreateException {
if (lastName == null) {
throw new javax.ejb.CreateException("欄位 \"lastName\" 不可為 null");
}
setLastName(lastName);
setFirstName(firstName);
return null; // 由容器生成主鍵
}
public void ejbPostCreate(java.lang.String lastName, java.lang.String firstName) {
// 關聯關係初始化
}
變更重點:移除 id 參數、回傳型別改為 java.lang.Object、移除設定 id 的程式碼。
CustomerLocalHome 介面:create 方法移除 id 參數;findByPrimaryKey 參數型別改為 java.lang.Objectejb-jar.xml:General 分頁將 Primary key class 改為 java.lang.Object;XML 原始碼視圖刪除 primkey-field 元素CustomerFacade,僅含遠端介面CustomerLocalHome:右鍵類別選 企業資源 > 呼叫企業 Bean 選擇 CustomerEBprivate CustomerLocalHome customerHome,在 ejbCreate 中初始化public void createCustomer(String lastName, String firstName) throws Exception {
customerHome.create(lastName, firstName);
}
public Collection getLastName(String firstName) throws Exception {
ArrayList names = new ArrayList();
Iterator it = customerHome.findByLastName(firstName).iterator();
while (it.hasNext()) {
names.add(((CustomerLocal) it.next()).getLastName());
}
return names;
}
NetBeans 4.1 已知問題:建立連線池時 MySQL 的 DataSource 類別名稱錯誤。需手動修正:
connection-pool-mysql.sun-resourcecom.mysql.jdbc.jdbc2.optional.MysqlDataSourceCustomerFacadeBean 產生 JUnit 測試 (工具 > JUnit 測試 > 建立測試)private CustomerFacadeRemote customerFacadesetUp() 取得遠端介面:protected void setUp() throws Exception {
InitialContext ctx = new InitialContext();
Object obj = ctx.lookup("ejb/CustomerFacadeBean");
customerFacade = ((CustomerFacadeRemoteHome)
PortableRemoteObject.narrow(obj, CustomerFacadeRemoteHome.class)).create();
}
public void testCreateCustomer() throws Exception {
System.out.println("PK:" + customerFacade.createCustomer("Foo", "Bar"));
}
public void testGetCustomerName() throws Exception {
long id = customerFacade.createCustomer("Joe", "User");
assertEquals(1, getLastName("name").length());
}
appserv-rt.jar (伺服器 lib 目錄)PK: 1123065661713
Testsuite: org.bank.CustomerFacadeBeanTest
Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 3.855 sec
BUILD SUCCESSFUL (total time: 6 seconds)
主鍵值 1123065661713 為伺服器自動生成的唯一值。