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 requested tables with following DDL:
          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.
  • Generete CMP beans from database and make changes that are described in above tutorial.
  • Add session facade bean and implement business method that creates order:
          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());
            }
        }  
      
  • Write client or JUnit tests and check the bean's functionality. Sources and tests are avalaible here.
Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

pblaha

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks