Tuesday December 06, 2005
How to use CMP beans with generated primary key I saw a question about using CMP beans with generated primary key. Therefore, I decided to write one simple application that can explain how to use this feature. More info about generating primary key values in CMP beans is avalaible here here. I would like to note that the user should never rely on the internals of the container code. And if the user chooses to use a generated PK for CMP, it means they do not care about the value, and should not try to access it (other
than as an Object).
In this post we will develop EJB module that creates product and purchase order. See Entity relationship diagram:
CREATE TABLE PRODUCT(
ID BIGINT(19) NOT NULL,
PART_NUMBER VARCHAR(19) UNIQUE NOT NULL,
DESCRIPTION VARCHAR(25),
PRICE FLOAT,
PRIMARY KEY (ID),
INDEX PART_NUMBER (PART_NUMBER)
);
CREATE TABLE PURCHASEORDER(
ID BIGINT(19) NOT NULL,
CUSTOMER VARCHAR(20) NOT NULL,
PRODUCT_ID BIGINT(19) NOT NULL,
AMOUNT FLOAT,
PRIMARY KEY (ID),
INDEX CUST (CUSTOMER),
FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCT(ID))
Primary key column should be mapped to column with NUMERIC data type with a precision of 19 or more.
public void createProduct(String partNr, String description, float price) throws EJBException {
try {
productHome.create(partNr,description, new Float(price));
} catch (CreateException ex) {
ex.printStackTrace();
throw new EJBException(ex.getMessage());
}
}
public void createOrder(String customer, String partNr, float amount) throws EJBException {
try {
ProductLocal product = productHome.findByPartNumber(partNr);
purchaseHome.create(customer,new Float(amount),product);
} catch (FinderException ex) {
ex.printStackTrace();
throw new EJBException(ex.getMessage());
}catch(CreateException ex){
ex.printStackTrace();
throw new EJBException(ex.getMessage());
}
}