Sei sulla pagina 1di 454

Oracle9i JDeveloper: Develop Applications with BC4J

Instructor Guide

D12867GC10 Edition 1.0 July 2002 D37337

Author Gary Williams

Copyright Oracle Corporation, 2002. All rights reserved. This documentation contains proprietary information of Oracle Corporation. It is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the following legend is applicable: Restricted Rights Legend Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights software under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software (October 1988). This material or any portion of it may not be copied in any form or by any means without the express prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties. If this documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with Restricted Rights, as defined in FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987). The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Education Products, Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065. Oracle Corporation does not warrant that this document is error-free. SQL, PL/SQL, Oracle DBMS, Oracle Universal Data Server, Oracle Application Server, LiveHTML are trademarks or registered trademarks of Oracle Corporation. All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Technical Contributors and Reviewers Anna Atkinson Blaise Ribet Cynthia Alford Holger Dindler Rasmussen Ken Cooper Lauri Boyd Monica Motley Publisher Michael Sebastian

Preface

Preface - 2

Profile How This Course Is Organized Oracle9i JDeveloper: Develop Applications with BC4J is an instructor-led course featuring lectures and hands-on exercises. Online demonstrations and written practice sessions reinforce the concepts and skills introduced.

Preface - 3

Related Publications Additional Publications System release bulletins Installation and users guides Read-me files International Oracle Users Group (IOUG) articles Oracle Magazine

Preface - 4

Typographic Conventions Typographic Conventions In Text Convention Bold Element Example

Emphasized words and phrases To navigate within this application, do in Web content only not click the Back and Forward buttons. Glossary terms (if there is a glossary) Key names Buttons, check boxes, triggers, windows
The algorithm inserts the new key.

Bold italic

Brackets Caps and lowercase

Press [Enter]. Click the Executable button. Select the Registration Required check box. Assign a When-Validate-Item trigger. Open the Master Schedule window.

Carets Commas

Menu paths Key sequences

Select File > Save. Press and release these keys one at a time: [Alt], [F], [D]

Preface - 5

Typographic Conventions (continued) Typographic Conventions In Text (continued)


Convention Courier New, case sensitive Object or Term Code output, SQL and PL/SQL code elements, Java code elements, directory names, filenames, passwords, pathnames, URLs, user input, usernames Example Code output: debug.seti (I,300); SQL code elements: Use the SELECT command to view information stored in the last_name column of the emp table. Java code elements: Java programming involves the String and StringBuffer classes. Directory names: bin (DOS), $FMHOME (UNIX) Filenames: Locate the init.ora file. Passwords: Use tiger as your password. Pathnames: Open c:\my_docs\projects. URLs: Go to http://www.oracle.com. User input: Enter 300. Usernames: Log on as scott. Initial cap Graphics labels (unless the term is a proper noun) Emphasized words and phrases in print publications, titles of books and courses, variables Key combinations Lesson and chapter titles in cross references, interface elements with long names that have only initial caps Customer address (but Oracle Payables)

Italic

Do not save changes to the database. For further information, see Oracle7 Server SQL Language Reference Manual. Enter user_id@us.oracle.com, where user_id is the name of the user. Press and hold these keys simultaneously: [Control] + [Alt] + [Delete] This subject is covered in Unit II, Lesson 3, Working with Objects. Select the Include a reusable module component and click Finish. Use the WHERE clause of query property.

Plus signs Quotation marks

Preface - 6

Typographic Conventions (continued) Typographic Conventions in Navigation Paths This course uses simplified navigation paths, such as the following example, to direct you through Oracle Applications. Example: Invoice Batch Summary (N) Invoice > Entry > Invoice Batches Summary (M) Query > Find (B) Approve This simplified path translates to the following: 1. (N) From the Navigator window, select Invoice > Entry > Invoice Batches Summary. 2. (M) From the menu, select Query > Find. 3. (B) Click the Approve button. Notation: (N) = Navigator (M) = Menu (T) = Tab (I) = Icon (H) = Hyperlink (B) = Button

Preface - 7

Preface - 8

Contents
Preface

1 Introduction to Business Components for Java


Objectives 1-2 Overview of J2EE 1-3 J2EE Tiers 1-4 Client Tier 1-5 Web Tier 1-6 Business Tier 1-7 J2EE Architecture 1-8 The Way Applications Are Built 1-9 Factor Common Code For Reuse 1-10 Refactor for Modularity 1-12 Refactor Common Queries 1-13 What Is a Framework-Based Development? 1-14 Understanding Framework-Based Programming 1-15 Refactor Common Queries 1-16 BC4J Implementation of This Pattern 1-17 Business Components for Java 1-18 Key Advantages of Business Components for Java 1-20 Business Components: A Closer Look 1-21 Entity Objects 1-22 View Objects 1-23 Application Module 1-24 Summary 1-25 2 Oracle JDeveloper9i Objectives 2-2 What Is an Integrated Development Environment (IDE) 2-3 JDeveloper9i 2-4 JDeveloper9i Features: Integrated Development Environment 2-5 The JDeveloper9i Environment 2-8 Project Organization: Workspaces 2-10 Project Organization: Projects 2-11 Project Organization: Structure Pane 2-12 Project Libraries 2-14 Creating New Components 2-16 Code Insight 2-17 CodeCoach 2-18 Building and Executing Java Programs 2-20

iii

JDeveloper9i Components 2-22 Developing Web Applications 2-24 Developing Java Client Applications 2-26 Developing Enterprise JavaBeans 2-28 Developing JavaBeans 2-29 Database Access 2-30 Using JavaDoc 2-32 Using the Help System 2-33 Searching the Help System 2-34 Summary 2-35 Practice 2-1 Overview 2-36 3 Developing a Business Components Application Objectives 3-2 Overview 3-3 Creating a Database Connection 3-4 How to Create a New Connection 3-5 How to Create a New Project Containing Business Components 3-7 The Business Components Project Wizard 3-8 How to Add Business Components to an Existing Project 3-9 What Has JDeveloper Created? 3-10 Generated Code 3-11 Viewing Information in the Structure Pane 3-13 How to Edit a Business Components Properties 3-14 The Business Component Browser 3-15 Running the Business Component Browser in Local Mode 3-16 How to Browse and Update Data in the Browser 3-17 Summary 3-18 Practice 3-1 Overview 3-19 Practice 3-1 3-20 4 Implementing Business Rules Objectives 4-2 Overview 4-3 Entity Object 4-4 Two Ways to Create an Entity Object 4-5 The Entity Object Wizard 4-6 Files Generated for the Customers Entity Object 4-7 The Supporting Java Classes 4-9 Assigning an Initial Value to an Entity Attribute 4-10 Mapping an Attribute to a Database Sequence 4-11 Practice 4-1 Overview 4-12 Validating Attributes 4-14

iv

ListValidator: Example 4-15 Using the Custom MethodValidator for an Attribute 4-16 Using the Custom MethodValidator for an Entity 4-17 Adding Custom Attribute Validation 4-18 Overriding EntityImpl Methods 4-19 Domains 4-20 Domains: Example 4-21 How to Create and Use the URLDomain 4-22 Where To Put Validation 4-23 Validation Order 4-25 Summary 4-26 Practice 4-2 Overview 4-27 Practice 4-2 4-28 5 Using Entity Associations in Business Logic Objectives 5-2 Associations 5-3 Association Example 5-4 Accessor Methods 5-5 Association Types 5-6 Deciding the Association Type 5-7 Creating Entity Associations 5-8 Traversing Associations: Source to Destination 5-12 Traversing Associations: Destination to Source 5-13 Summary 5-14 Practice 5-1 Overview 5-15 Creating and Managing Database Objects Objectives 6-2 Forward Engineering 6-3 Creating an Entity without an Underlying Database Object 6-4 Defining a New Entity Attribute 6-5 Creating the Entity 6-8 Creating a Database Table from the Definition of an Entity Object 6-11 About Entity Constraints 6-12 Creating an Entity Constraint 6-13 Creating a Database Constraint from the Definition of an Entity Constraint 6-14 Managing Schema Changes 6-15 Summary 6-17 Practice 6-1 Overview 6-18

Presenting Business Data Objectives 7-2 Overview 7-3 View Objects 7-4 Interaction Between Views and Entities: Retrieving Data 7-5 Interaction Between Views and Entities: Updating Data 7-6 Synchronization of View Objects 7-7 Creating a View Object Using the View Object Wizard 7-8 Classes Related to View Objects in oracle.jbo.server 7-9 Files Generated for the LineItemView View Object 7-10 Example of a View Object 7-11 Practice 7-1 Overview 7-12 Calculated Attributes in Views 7-13 View Links 7-14 Master-Detail Views 7-15 Traversing Links 7-16 Polymorphism 7-17 Implementing Polymorphic Rowsets 7-18 Creating HourlyEmployee 7-19 Creating SalariedEmployee 7-20 Adding Custom Methods 7-21 Create the View Object 7-22 Add Custom Methods to the View Object 7-23 Create a Test Client 7-25 The Results 7-28 Summary 7-29 Practice 7-2 Overview 7-30 Handling Business Components Transactions Objectives 8-2 Business Components Transactions 8-3 Application Modules 8-4 Application Module Transactions 8-5 Accessing a Transaction 8-7 Committing Transactions 8-9 Compositions and the Commit Cycle 8-10 Customizing the Post Phase 8-11 Customizing the Commit Phase 8-12 Locking Modes Supported by Business Components 8-13 Getting and Setting the Locking Mode 8-14 Application Module Pooling 8-15 Application Module Pooling: Default Behavior 8-17 Application Module Pool Parameters 8-18

vi

Managing Transaction State 8-20 Summary 8-22 Practice 8-1 Overview 8-23 9 Packaging Business Services and Data Models Objectives 9-2 Overview 9-3 Application Module 9-4 Designing Your Application Modules 9-5 Files Generated for the OrdModule Application Module 9-6 About the Data Model 9-7 Defining the Data Model 9-8 The Wizard Ensures a Valid Data Model 9-9 Nesting Application Modules 9-10 Adding Service Methods to an Application Module 9-12 Adding Custom Properties to an Application Module 9-13 Summary 9-14 Practice 9-1 Overview 9-15

10 Extending and Substituting Business Components Objectives 10-2 Overview 10-3 Using Existing Objects with your Objects 10-4 About Customization 10-5 Customization Concepts 10-6 Customizing an Application 10-7 Example of Customization 10-8 Looking at the XML 10-13 Factory Substitution 10-14 Example Using Factory Substitution 10-15 Performing Factory Substitution 10-16 The Finished Substitution 10-17 Looking at the XML 10-18 Summary 10-19 Practice 10-1 Overview 10-20 11 Deploying Business Components Applications Objectives 11-2 Overview 11-3 n-Tiered Business Components Architecture 11-4 Deployment Modes 11-5 Local Deployment 11-7 Creating a Local Deployment 11-8

vii

Web Module Deployment 11-9 Creating a Web Module Deployment 11-10 Creating a Connection to an Application Server 11-12 Deploying a Web Module 11-13 Remote Deployment 11-14 What Is a Remotable Application Module? 11-15 The Basic Architecture 11-16 Making an Application Module Remotable 11-17 Creating a Remote Application Module Deployment 11-19 Deploying a Remote Application Module 11-21 Testing a Remote Application Module Using the BC4J Tester 11-22 Summary 11-23 Practice 11-1 Overview 11-24 12 Creating Batch Clients and XML for a Business Components Application Objectives 12-2 Overview 12-3 Creating a Batch Client 12-4 Instantiating an Application Module 12-5 Finding and Instantiating a View Object 12-6 Finding Data by a Primary Key 12-7 Manipulating the Data 12-8 Calling Custom Methods 12-9 Application Module Methods 12-10 JDeveloper9i and XML 12-11 What Is XML? 12-12 XML Syntax Rules 12-13 A Customer Example 12-14 The BC4J Project XML File 12-15 XML Structure 12-16 Using BC4J to Output XML 12-18 BC4J and Java Messaging Service 12-21 Summary 12-23 Practice 12-1 Overview 12-24 13 Creating Custom and Dynamic Queries Objectives 13-2 SQL-Based View Objects 13-3 Creating a SQL-Based View Object 13-4 Expert-Mode View Objects 13-5 Mapping Attributes in Expert Mode 13-6 Maintaining Attribute Mappings in Expert Mode 13-7 Setting Parameters for the Where Clause 13-8

viii

Assigning Values to Queries with Parameters at Run Time 13-9 Setting Where and OrderBy Clauses at Run Time 13-10 Creating a New View Object at Run Time 13-11 Summary 13-12 Practice 13-1 Overview 13-13 14 Creating JSP Clients for a Business Components Application Objectives 14-2 What Is a JSP? 14-3 Invoking JavaServer Pages 14-4 Basic JSP Elements 14-5 Automated JSP Features 14-6 Example: The Date JSP Page 14-7 Scriptlets 14-10 Expressions 14-11 Declarations 14-12 Directives 14-13 Custom Tags 14-14 The BC4J-Based JSP Application 14-15 Example 14-16 JDeveloper Support for BC4J 14-17 Creating BC4J-based Applications 14-18 Invoking the JSP Application Wizard 14-19 Set the JSP Application Details 14-20 Select the BC4J Application Module 14-21 Select Form Types 14-22 Generated Files 14-23 Completed JSP Application 14-25 What the End User Sees 14-26 BC4J Data Tags 14-27 Manually Creating BC4J Applications 14-28 The releasemode attribute 14-29 Manually Creating BC4J Applications 14-30 Practice 14-1 Overview 14-31 Component Tags 14-33 Using Component Tags 14-35 How Component Tags Work 14-36 Component Tag JSP 14-37 Practice 14-2 Overview 14-39 15 Creating a JClient Application for a Business Components Application Objectives 15-2 Overview 15-3

ix

What Is JClient? 15-4 What Are the Components of JClient? 15-5 JClient Architecture 15-6 How Is JClient Related to BC4J? 15-7 JClient Model 15-8 JClient Operational Overview 15-9 A Simple JClient Form 15-10 Creating a Simple JClient Form 15-11 What Files Has JDeveloper Generated? 15-13 Client Project File 15-14 Summary 15-15 Practice 15-1 Overview 15-16 Practice Overview 15-17 16 Business Component Applications Best Practices Objectives 16-2 Put Business Logic in the Right Place 16-3 Use Interfaces 16-5 Deployment Configuration 16-6 Use Application Module Pooling 16-7 SQL-Only Views 16-9 Application Module Size 16-10 Query Conditions 16-11 Summary 16-12 A Appendix A: Order Entry Schema B Appendix B: Practice Solutions

Introduction to Business Components for Java

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 60 minutes 60 minutes

Topic Lecture Total

Objectives
After completing this lesson, you should be able to do the following: Define J2EE technologies Describe middle-tier design and architecture Describe an application framework Describe the BC4J architecture

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson gives you a high-level understanding of the Business Components for Java (BC4J) framework. It teaches the main concepts behind Business Components for Java. It also describes the different components in the framework.

Oracle9i JDeveloper: Develop Applications with BC4J 1-2

Overview of J2EE
What is J2EE? An architecture for developing, deploying, and executing Web-enabled applications in a distributed environment Provides a component-based approach for:
Design Development Assembly Deployment of enterprise applications

Uses a multitier distributed application model Is a specification for component containers

Copyright Oracle Corporation, 2002. All rights reserved.

Overview of J2EE J2EE (Java 2, Enterprise Edition) was designed to provide multiplatform support for developing and deploying multitier enterprise-level applications. Typically these applications include a client-side application to manage user interface issues, one or more middle-tier modules to handle business logic and client services, and a backend enterprise information system to provide data services. The J2EE platform also provides a component-based environment for the full life cycle of an application system. This includes design, development, assembly, and deployment. The J2EE platform uses a multitier distributed application model. The multitier model means that the application can be segmented to run on multiple devices. These devices, or platforms, can be chosen based on their specific ability to perform a given task. J2EE is also a specification that defines component containers. Containers are a run-time environment that provide a set of standardized component services. For example, a J2EE Web container must provide run-time support for handling client requests and returning results to the client.

Oracle9i JDeveloper: Develop Applications with BC4J 1-3

J2EE Tiers
Client tier
Application clients HTML clients XML, WML, WAP

Web tier
Java Servlets JavaServer Pages

Business tier
Session beans Entity beans Enterprise JavaBeans

Enterprise Information tier


Copyright Oracle Corporation, 2002. All rights reserved.

J2EE Tiers The J2EE architecture is composed of a number of tiers. Specifically it is composed of a client tier, a middle tier, and a backend tier. Each tier is made up of several sub-tiers. The client tier contains stand-alone application clients, HTML clients, applets and others. The middle tier has several sub-tiers, including the Web tier and the business logic tier. The Web tier includes Java Servlets and JavaServer Pages. The Business tier includes server-side technologies such as Session beans, Entity beans, Enterprise JavaBeans component containers. This tier provides transaction and persistence services in addition to standard services. The Enterprise Information tier provides the persistence layer to J2EE applications. Note XML (Extensible Markup Language) is a markup language similar to HTML. The difference is that XML is extensible which means you can create your own tags. You can therefore customize an XML document to contain tags to describe your specific business data. XML documents must also follow strict syntax rules unlike HTML. WML (Wireless Markup Language) is a language that allows text portions of Web pages to be presented on small wireless devices such as cellular telephones and personal digital assistants. It is part of the larger Wireless Application Protocol (WAP) which specifies communication standards for wireless devices.

Oracle9i JDeveloper: Develop Applications with BC4J 1-4

Client Tier
Thin client using a lightweight interface Heavyweight operations are performed on a J2EE server
Client tier Application Client Applets Web browser JavaBeans Wireless clients Web tier Business tier

J2EE server
Copyright Oracle Corporation, 2002. All rights reserved.

Client Tier The J2EE client tier supports a number of platforms from desktop machines to cellular telephones, to wireless devices. The client application makes a request to the server at the users request, and presents the results back to the user. The request can be sent to any J2EE tier including a Web tier or business tier. Because the client application is what the user interacts with, it is important to select the most appropriate platform for your application. It should be one that best meets the requirements of the application and provides a solid user interface. The client tier can be a Java application client, an Applet, a JavaBean, or an HTML client via a Web browser.

Oracle9i JDeveloper: Develop Applications with BC4J 1-5

Web Tier
JavaServer Pages Servlets
Client tier Application Client Applets Web browser JavaBeans Wireless clients JavaServer Pages Servlets

Web tier

Business tier

JavaBeans

J2EE server
Copyright Oracle Corporation, 2002. All rights reserved.

Web Tier The Web tier is generally dedicated to handling an applications presentation logic. That is, it is responsible for delivering dynamic content to the requesting client. In most cases, this is done by JavaServer Pages and Servlets. This handling of dynamic content is also supported by the use of JavaBeans. This model of handling presentation logic provides the ability to decouple data access issues with those surrounding end-user interactions. This separation of business logic and presentation logic allows for more scalable, robust, and maintainable applications.

Oracle9i JDeveloper: Develop Applications with BC4J 1-6

Business Tier
Enterprise JavaBeans
Web tier Client tier Application Client Applets Web browser JavaBeans Wireless clients Business tier

JSP Pages Servlets

Entity beans
JavaBeans

Session beans

J2EE server
Copyright Oracle Corporation, 2002. All rights reserved.

Business Tier The Business tier supplies containers that can host objects that manage presentation-independent business logic, as well as provide transaction and persistence services. This tier hosts Enterprise JavaBeans (EJB) components. The Enterprise JavaBeans architecture is the server side technology in this multitier J2EE model. It provides the technology to develop and deploy components that contain the business logic of an enterprise application. By deploying business logic in this tier, they are independent of presentation, client, and persistence tiers. This makes them scalable and secure. EJB components contain business rules and logic. They can be changed without affecting the presentation or client tiers.

Oracle9i JDeveloper: Develop Applications with BC4J 1-7

J2EE Architecture
J2EE server
Servlet Browser JSP page

Web container (Web tier)

Application client Application Client container Client machine Enterprise Bean Enterprise Bean

EJB container (Business tier)

Copyright Oracle Corporation, 2002. All rights reserved.

J2EE Containers In traditional application development, the developer must write code to handle transactions, resource pooling, multithreading, state management, and many other low-level tasks to make the application successful. This approach is expensive, time consuming, and can be error prone. The J2EE architecture provides these services and many others at each level in the multitier environment. Because these services are provided, the application developer is now free to concentrate on writing code to implement business logic instead of software management logic. The J2EE architecture comprises several components: Application client container: Manages the execution of client components. Supplies services used to connect to other container objects. Application clients and the container run on the client machine. J2EE Server: Is the run-time component of a J2EE product. It provides EJB and Web containers. Web container: Manages the execution of Servlets and JavaServer Pages. It provides services used to connect to other container objects. It runs on the J2EE Server. EJB container: Manages the execution of Enterprise JavaBeans. It provides services used to connect to other container objects. It runs on the J2EE Server.

Oracle9i JDeveloper: Develop Applications with BC4J 1-8

The Way Applications Are Built


Access customer data from a query. Perform customer validation and processing. Save customer changes to the database.
Customers (SQL)
V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

JSP

ers tom us

Copyright Oracle Corporation, 2002. All rights reserved.

The Way Applications Are Built On the next few pages, you will learn how applications are usually built. It is a bit of an iterative process where common elements are factored or abstracted to a level where they can be shared by multiple components. In the example, the application being built retrieves data from a Customers table. The application is a simple JSP. It access data from a query against the Customers table, performs the required validation, and saves changes to the database.

Oracle9i JDeveloper: Develop Applications with BC4J 1-9

Factor Common Code For Reuse


Remove common logic and persistence code. Both clients use the same data validation.

Agents (SQL)

Customers (SQL)

JSP

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

ers tom us

Copyright Oracle Corporation, 2002. All rights reserved.

Factor Common Code for Reuse After the initial application is complete, you can see that there are other client applications that use the same base table and validation rules. To make this application more maintainable and scalable, you should remove the persistence and validation, and place the code in a common routine.

Oracle9i JDeveloper: Develop Applications with BC4J 1-10

Factor Common Code For Reuse


Add code to access the Orders table. All clients use the same validation code.
Customer Orders (SQL) NewOrders (SQL)

Agents (SQL)

Customers (SQL)

JSP

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

rs de Or

ers tom us

Copyright Oracle Corporation, 2002. All rights reserved.

Factor Common Code for Reuse (continued) As you would expect, the needs of the application continue to grow. This time you need to access the orders that a customer has placed, in addition to the customer information. To keep the validation in a singular module, you can add code-common logic to validate the order information in addition to the customers data. All the clients now share the same validation logic.

Oracle9i JDeveloper: Develop Applications with BC4J 1-11

Refactor for Modularity

(SQL) Separate tablespecific logic and NewOrders (SQL) persistence. Clients use only the code they need. Orders Logic and Persistence Customer Orders

Agents (SQL)

Customers (SQL)

JSP

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

Customers Logic and Persistence

rs de Or

ers tom us

Copyright Oracle Corporation, 2002. All rights reserved.

Refactor for Modularity As the application continues to grow in complexity, you find that you need to separate the tablespecific business logic and persistence for each of the tables. This gives clients easier and cleaner access to persistence and validation logic they need. This modularity also provides a single place for business logic for each of the components of your persistence layer, which make maintenance more manageable.

Oracle9i JDeveloper: Develop Applications with BC4J 1-12

Refactor Common Queries


Customer Orders NewOrders Agents Customers

JSP

SQL

SQL

Reusable Query

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

Orders Logic and Persistence

Customers Logic and Persistence

rs de Or

ers tom us

Copyright Oracle Corporation, 2002. All rights reserved.

Refactor Common Queries On closer examination, you discover that several of your client applications use the same or at least very similar queries. The next step in making the application more modular and maintainable is to refactor for common queries. In this example, the Customers and Agents clients use the same query. You can now create a single Customers query module that handles access to the Customers table. Likewise, the Customer Orders and New Orders clients use a similar query. You can create a single query that will provide data to both of those clients.

Oracle9i JDeveloper: Develop Applications with BC4J 1-13

What Is a Framework-Based Development?


A framework: Is a set of intelligent cooperating software components Is designed to be specialized for your business Handles the majority of common tasks with sensible behavior Allows easy customization of default behaviors

Copyright Oracle Corporation, 2002. All rights reserved.

What Is a Framework-Base Development? Framework-based development provides software components that are designed to help make modularizing and factoring easy or even automatic. A framework provides defined components that fill specific niches in the process of developing software solutions, such as queries, business logic and validation, and persistence management. The software components should be intelligent and integrate with all other components in the framework. The components must support easy customization to meet your specific business needs. The framework should also handle the majority of common tasks with sensible and expected standard behavior. There should be a minimum of customization required for default behaviors for most applications. However, if the default behaviors do not meet specific application requirements, they should be easy to customize.

Oracle9i JDeveloper: Develop Applications with BC4J 1-14

Understanding Framework-Based Programming


Provides base functionality
Standard behaviors Data access methods Transaction management

You can augment or circumvent base functionality Provides hook points to standard functions Your objects have only your code No messy code generation

Copyright Oracle Corporation, 2002. All rights reserved.

Understanding Framework-Based Programming A framework provides behind-the-scenes code to manage base functionality. These functions include standard behaviors such as data validation and business logic checks. They also include data access methods and transaction management. With these built-in functions and methods, the software developer can concentrate on building software specific to their business instead of low-level programming to manage the software environment. A framework not only provides for this base functionality but it is also easily customizable. You can augment or even circumvent base functionality as your business rules dictate. A framework also provides hook points to standard functions. These hooks allow you to add behaviors to existing standard functions. For example, you should be able to easily add an audit trail procedure to the existing standard commit function. Another important aspect of a framework is that objects that you create should contain your code only. This isolates your code and keeps it from becoming confused with the framework code. Nothing you can do in your code will break the framework. There is no code generation that you must wrap around your custom code.

Oracle9i JDeveloper: Develop Applications with BC4J 1-15

Refactor Common Queries


Customer Orders NewOrders Agents Customers

JSP

SQL

SQL

Reusable Query

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

Orders Logic and Persistence

Customers Logic and Persistence

rs de Or

ers tom us

Copyright Oracle Corporation, 2002. All rights reserved.

Refactor Common Queries Earlier in this lesson, you saw the steps required to build a growing application by factoring common queries and modularizing business logic and persistence. The result is an application that has a modular or object flavor but is not very reusable. Although the individual components are reusable, the structure is not. When you need to add components for products and inventory items, you will need to write much of the same code again. The differences will be the underlying tables and the validation logic.

Oracle9i JDeveloper: Develop Applications with BC4J 1-16

BC4J Implementation of This Pattern


JSP

Orders (SQL)

Customers (SQL)

Reusable Query Components

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^ V^V^V^V^V^V^V^V^V^V^ V^V^V^V V^V^V^ ^V^V^V^V^V^V^ V^V^V^V^V^V^ V^V^ V^V^V^V^

Reusable Business Logic and Persistence Components

rs de Or

ers tom us

Copyright Oracle Corporation, 2002. All rights reserved.

BC4J Implementation of this Pattern Business Components for Java (BC4J) is Oracle's Java development framework. BC4J implements the example application with components built on top of the framework. The components are reusable query objects and reusable business logic components. Each component provides standard functionality and can be easily modified. The components allow for your customization to be completely independent of the framework so your code is completely isolated from the framework. This makes modification and maintenance of custom code easy to manage. BC4J not only provides the base on which to build this application, but the framework is completely reusable. In other words, the low-level coding to manage transactions, database interaction, business logic encapsulation in written for you and can be used for any application.

Oracle9i JDeveloper: Develop Applications with BC4J 1-17

Business Components for Java


Business Components for Java: Is a framework for the productive development of J2EE applications Is an out-of-the-box solution for:
Optimized database interaction Business logic encapsulation User interface development J2EE deployment Scalability and performance

Copyright Oracle Corporation, 2002. All rights reserved.

Business Components for Java The aim of Business Components for Java is to make your job easier. By providing the fundamental structures required for any application, BC4J allows you to concentrate your efforts on writing only the code that is specific to your business. One of the biggest advantages of using Business Components for Java is that code that you would usually write yourself is provided for you. This eliminates the need for handwritten database access code, which saves time and avoids bugs. The low-level database access code is written to take advantage of as many application tuning procedures as possible. BC4J also provides components that are specifically designed to encapsulate your business logic and to isolate it from other parts of the framework. This makes your code more manageable and maintainable. Because the BC4J application is built for tier independence, it provides consistent business logic across all client applications. The BC4J application is completely user-interface independent. After you have written a business components application, it is easy to deploy your application in different ways, with different client interfaces. JDeveloper9i includes wizards and utilities, which you can use to build user interfaces that use an application built with BC4J components. This saves you time and effort in building client applications.

Oracle9i JDeveloper: Develop Applications with BC4J 1-18

Business Components for Java (continued) JDeveloper9i also provides built-in utilities and wizards for deploying J2EE-compliant applications. You can easily deploy a BC4J application as a simple .jar file or to a J2EE application server such as Oracle9iAS. Because BC4J is written for tier independence, you can deploy the application in many different ways without any changes to your code.

Oracle9i JDeveloper: Develop Applications with BC4J 1-19

Key Advantages of Business Components for Java


Incorporates reusable business logic Handles database transactions Separates business logic from data presentation Is a component-based architecture Supplies most of the code that you need in your application Provides flexibility Uses SQL-based data views Is user-interface independent Is completely independent of the deployment target
Copyright Oracle Corporation, 2002. All rights reserved.

Advantages of Business Components for Java One of the key advantages to BC4J is that it incorporates reusable business logic. After you create a component to enforce your business logic, you can reuse that component throughout your application or use it in other applications. BC4J has built-in database transaction management functions so you do not have to write low-level database access routines. Because of the object-oriented design of BC4J, the business logic is completely separated from the presentation logic. This gives you the ability to easily adjust business rules and logic without affecting the presentation layer. BC4J also uses SQL-based data views, so your data views can be based on any valid SQL statement. This gives you the flexibility to create data views with as much or as little complexity as needed to meet your business needs. Because BC4J is object oriented and built as a logical middle tier, it is completely independent of the user interface and deployment target platform. No matter what the interface will be or where the application will be deployed, the BC4J components remain the same.

Oracle9i JDeveloper: Develop Applications with BC4J 1-20

Business Components: A Closer Look


Application module OrderEntryApp View objects PriorityOrder Entity objects Customers Orders OrderItems ItemList Application tasks Transaction handling
Reusable Query Components

Reusable Business Logic and Persistence Components

Copyright Oracle Corporation, 2002. All rights reserved.

Business Components A business component application is made of a number of components: entity objects and view objects are the major components. Each component has its own role in your application: Entity objects encapsulate your business entities; each one maps to a data source. View objects join, filter, and sort data for a particular task or scenario in your application. Application modules package all the components in an application. They also implement the transaction handling for the whole application. These and other components are covered in much more detail in later lessons.

Oracle9i JDeveloper: Develop Applications with BC4J 1-21

Entity Objects
Encapsulate business logic Cache data Implement validation rules

Entity objects Customers Orders OrderItems

Reusable Business Logic and Persistence Components

Copyright Oracle Corporation, 2002. All rights reserved.

Entity Objects Entity objects are the first components that you create when building a business components application. Each entity object represents a business object, or business entity, in your application. For example, in an online ordering system, you might have a customers entity and an orders entity. Each entity object maps to a data source, usually a database table or database view. Entity objects cache data before committing any changes to the database. Entity objects also handle business rules and validation. Associations An association is a business component that defines a master-detail relationship between two entity objects. Associations enable you to traverse related entity objects in your application.

Oracle9i JDeveloper: Develop Applications with BC4J 1-22

View Objects
Present the details of business data that are needed, by providing a view of entity objects Have master-detail relationships that are coordinated by view links Are easily customizable

View objects PriorityOrder ItemList

Reusable Query Components

Copyright Oracle Corporation, 2002. All rights reserved.

View Objects A view object represents a view or slice of your data. View objects join, filter, and sort data to give you the right view of data for the task at hand. For example, your application might contain a form to view and update priority orders. For this you could create a PriorityOrder view object and base your application form on it. Each view object contains a SQL query and is bound to one or more entity objects. For example, the PriorityOrder view could get data from the customers and orders entity objects. View Object Attributes A view object can contain two types of attributes: Attributes based on an attribute of an entity object Calculated attributes, which are based on a SQL-calculated field View Links A view link is a business component that defines a master-detail relationship between two view objects. Instructor Note You can create a view object that is not based on an entity object. This type of view object is called a SQL-based view object, and it is always read-only. SQL-based view objects are covered in a later lesson.

Oracle9i JDeveloper: Develop Applications with BC4J 1-23

Application Module
Defines the logical data model and business methods needed to support an application task Handles transactions Interacts with clients

Application Module

OrderManagementApp

Copyright Oracle Corporation, 2002. All rights reserved.

Application Modules An application module defines the data model, business logic, and methods needed to support an application task. For example, OrderManagementApp supports the task of managing orders in the online orders system. The application module defines the database session and controls database locks. This means that your application task runs in one database session. You can add methods to the application module to perform any processing that applies to the whole application task. You can also nest application modules; for example, OrderManagementApp could be nested inside another application module called OnlineOrdersApp.

Oracle9i JDeveloper: Develop Applications with BC4J 1-24

Summary
In this lesson, you should have learned how to: Define the J2EE architecture and technologies Describe middle-tier design and architecture Describe an application framework Describe the BC4J Architecture

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 1-25

Oracle JDeveloper9i

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 40 minutes 30 minutes 70 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Create workspaces and projects Build, execute, and debug Java applications Access Help topics and Javadoc Use JDeveloper9i productivity features to enhance program development

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson provides a review of Oracle JDeveloper. The lesson shows you how to use JDeveloper9i to manage multiple Java programming efforts. The lesson explores workspaces, projects, and applications. It also shows you how to use the JDeveloper9i integrated development environment (IDE) to view and edit source code.

Oracle9i JDeveloper: Develop Applications with BC4J 2-2

What Is an Integrated Development Environment (IDE)


Is a software development environment Supports complete development life cycle Supports Java, HTML, XML, UML Provides database interaction Allows customization of the interface Provides wizards and navigators that make software development easier and reproducible

Copyright Oracle Corporation, 2002. All rights reserved.

Building Applications with Oracle JDeveloper9i You can use Oracle JDeveloper9i to build a number of different types of Java components. This lesson focuses on using the JDeveloper9i IDE for building applications. What Is a Wizard? A wizard is a graphical tool that guides you step by step through the process of defining a new element in the IDE. Oracle JDeveloper9i provides a number of wizards, including: Project Wizard: Defines a new project Application Wizard: Defines a new Java application Applet Wizard: Defines a new Java applet EJB Wizard: Defines a new Enterprise JavaBean Designing a User Interface with Oracle JDeveloper9i Oracle JDeveloper9i provides an interface designer for designing the visual parts of your program. By using JDeveloper9i, you can specify the following features of the user interface: Size and position of visual controls Properties for each control, such as labels, enabled and disabled status, font, and so on Event handler methods
Oracle9i JDeveloper: Develop Applications with BC4J 2-3

JDeveloper9i
Is an integrated development environment Use to develop, debug and deploy:
Java client applications Servlets JavaServer Pages UIX pages Enterprise JavaBeans

Supports version control and management Provides database access and support Has a customizable interface Supports complete development life cycle
Copyright Oracle Corporation, 2002. All rights reserved.

JDeveloper JDeveloper9i is a full-featured, visual development environment for creating multitier Java applications. With JDeveloper9i you can develop, debug, and deploy client applications, dynamic HTML applications, Web and application server components and database-stored procedures based on industry-standard models. You can build applications with JDeveloper9i that use a logical multitier architecture that includes a client, presentation server, application server, and database components. You can deploy these logical components to whatever physical tiers are appropriate at the time of deployment.

Oracle9i JDeveloper: Develop Applications with BC4J 2-4

JDeveloper9i Features: Integrated Development Environment


Core technologies
Java XML

Multiple clients
Browser, Java applications, Applets, Web services

Complete development lifecycle


Model, build, deploy, debug, tune

Multiple development operating system support


Windows, Linux, UNIX

Oracle platform support


Application server and database
Copyright Oracle Corporation, 2002. All rights reserved.

Integrated Development Environment JDeveloper9i is a complete Java development IDE based on Java and XML. It supports the creation of multiple types of client applications including JSPs, Java applications, Applets, and Web services. It provides an environment which can be used for the complete life cycle of an application. It can be used to model, build, debug, tune, and deploy Java applications. Because it is a Java application, it can run on any platform that supports a JVM such as Windows, Linux, and UNIX.

Oracle9i JDeveloper: Develop Applications with BC4J 2-5

JDeveloper9i Features: Integrated Development Environment


Two-way technology Dockable interfaces Visual debugger Code Insight CodeCoach Multiple workspaces Multiple projects Multiple libraries JDeveloper9i Addin API

Copyright Oracle Corporation, 2002. All rights reserved.

Integrated Development Environment (continued) JDeveloper9i is a visual programming tool with an integrated project navigator, code editor, debugger, and compiler. It also provides wizards, form designers, and property and event editors to automate many programming tasks. Two-Way Technology: The JDeveloper9i IDE employs two-way technology that keeps code and design synchronized as a developer works. Changes made in the RAD-style designer are immediately reflected in the code. Similarly, changes to the code are immediately displayed in the Visual Designer. Modifications to JavaBean properties are reflected both programmatically and in the visual property editor. A structured view of all projects shows each class and its methods, properties, and inheritances, all of which are kept in sync with the project code and design as the developer works. Docking MDI Interface: The JDeveloper9i development tool is a Multiple Document Interface (MDI), allowing developers to quickly switch among editors and designers. The Navigator, Property Inspector, and debugging message windows are dockable palette windows. This flexibility enables developers to be most productive by customizing their environment specific to a stage in the project cycle or an individuals role.

Oracle9i JDeveloper: Develop Applications with BC4J 2-6

Integrated Development Environment (continued) Visual Debugger: The visual integrated debugger supports breakpoints, evaluations, watches, and a wide variety of control flow commands. The visual debuggers support both JDK 1.1 and Java 2. Remote debugging of server-side Java, and of servlets and JSP pages running on various Web servers, is also supported. Code Insight: When the editor window is open for coding, the JDeveloper9i IDE optionally displays coding tips, including parameter lists and class members. A package explorer shows all available packages on the current class path.

Oracle9i JDeveloper: Develop Applications with BC4J 2-7

The JDeveloper9i Environment

Copyright Oracle Corporation, 2002. All rights reserved.

The Oracle JDeveloper9i Environment JDeveloper9i contains four major user interface components. You use these components to edit code, design, and manage the user interface and to navigate around your program. The Main Window The main window in JDeveloper9i acts as the control center. It contains the main menu and a toolbar with shortcuts to commonly used menu items. The main window also holds the component palette, which contains components such as buttons, grids, and so on. The Project Navigator Window The Project Navigator window is made up of two components. The Navigator pane shows a list of files or classes in a project. The files may be Java source files, .class files, graphics files, HTML documents, and so on. The Structure pane lists all the methods, attributes, and graphical user interface (GUI) components in a selected class. It lists the structure elements in an XML file. Most of the work takes place through editors, which you use to write code and design user interfaces. To open a specific editor, right-click a component and select the editor from the shortcut menu. The options are generally the Code editor, Class editor, and the UI editor.

Oracle9i JDeveloper: Develop Applications with BC4J 2-8

The Oracle JDeveloper9i Environment (continued) Property Inspector The Property Inspector is the pane that shows the properties and events associated with a selected component in the design section of a viewer.

Oracle9i JDeveloper: Develop Applications with BC4J 2-9

Project Organization: Workspaces


Workspaces Workspaces organize your work. Navigator The navigator pane supports multiple open workspaces. Each workspace Structure can contain pane multiple projects. A workspace stores environment settings.

Copyright Oracle Corporation, 2002. All rights reserved.

Project Organization Oracle JDeveloper9i uses a well-defined structure to manage Java programming projects. The structure is hierarchical and consists of workspaces, projects, applications, images, HTML files, and more. Workspaces The workspace is the highest level of the control structure. A workspace keeps track of the projects you use and the environment setting while developing your Java program. When you open JDeveloper9i, the last workspace used is opened by default, enabling you to start where you left off. Workspaces are stored in files with the extension .jws. You do not edit a workspace file directly. Whenever you save your workspace, all of the current open files and window positions and sizes are stored for you. Saving the workspace saves only the current environment configuration, not the open files. To save the open and modified files, select Save or Save All from the File menu. Instructor Note Demonstrate how to create a workspace.

Oracle9i JDeveloper: Develop Applications with BC4J 2-10

Project Organization: Projects


Projects contain related files. Manage:
Environment variables Compiler and debug options

Projects Navigator pane

Use projects to logically group elements of the application.

Structure pane

Copyright Oracle Corporation, 2002. All rights reserved.

Project Organization: Projects JDeveloper9i projects organize file elements used to create your program. A project file has the file extension .jpr and keeps track of the source files, packages, classes, images, and other elements that may be needed for your program. You can add multiple projects to your workspace to easily access, modify, and reuse your source code. Projects also manage environment variables such as the source and output paths used for compiling and navigating your program. They also maintain compiler, run-time, and debugging options so that you can customize the behavior of those tools in each project. In the Navigator pane, projects can be found at the second level in the hierarchy under the workspace. You can use projects to logically group different elements of an application. You can place Business Components for Java in one project while you place the user interface portions in another. This mirrors the desired logical separation of user interface components and business logic. You can then deploy each of the projects separately or together, whichever technique fits your deployment model. Instructor Note Demo creating an empty Project.
Oracle9i JDeveloper: Develop Applications with BC4J 2-11

Project Organization: Structure Pane

Select the item in the structure pane.

Copyright Oracle Corporation, 2002. All rights reserved.

Project Organization: Structure Pane JDeveloper9i makes it easy to examine methods and variables in a Java program. The bottom part of the Navigator window is the Structure pane. The Structure pane displays structural information about the Java code in a file, such as: Imported packages The classes and interfaces in the file Any ancestor classes and interfaces Variables and methods XML tags and attributes This structural analysis is displayed in the form of a hierarchical tree, much like a table of contents for the file. The Structure pane displays the structure of your file and provides quick access to the location of and details concerning elements within the current file. For example, if you select a .java file in the Navigator pane, its classes, variables, and methods are displayed in the Structure pane. You can double-click any of those elements in the Structure pane and, in the Source Editor, JDeveloper9i moves to and highlights that element in the content viewer.

Oracle9i JDeveloper: Develop Applications with BC4J 2-12

Project Organization: Structure Pane (continued) For example, if you double-click the getName() method in the Structure pane, JDeveloper9i takes you to the definition of that item in the source code, displaying and highlighting it in the content viewer. The Structure pane provides a much faster way to browse and find the elements of a .java file than scrolling through it or searching for a word.

Oracle9i JDeveloper: Develop Applications with BC4J 2-13

Project Libraries

Copyright Oracle Corporation, 2002. All rights reserved.

Project Libraries Class libraries provide a convenient way to define paths to compiled classes, source files, and javadoc files. When you add or remove a library in your JDeveloper9i project, the class, source and javadoc path statements used to compile and execute your code are updated accordingly. JDeveloper9i comes with a standard set of libraries. You can add these libraries to your project through the Project Properties dialog box, or use the dialog box to create your own custom library definitions. To add a standard library to your project: 1. Select Project > Project Settings from the menu. 2. Click the Libraries node in the navigator tree. 3. Select the desired library from the Available Libraries list and use the arrow key to move it to the Selected Libraries list. To add a custom library definition to your project: 1. Click New. 2. In the New Library dialog box, enter the Name, Location, Class Path, Source Path and Doc Path for your library. 3. Click OK.
Oracle9i JDeveloper: Develop Applications with BC4J 2-14

Project Libraries (continued) The library is automatically added to both the list of Available Libraries and the list of Selected Libraries. Once a custom library has been added to the list of Available Libraries, it is available to add to any project in any workspace. JDeveloper will automatically add the required libraries to your project when you add components from the component palette.

Oracle9i JDeveloper: Develop Applications with BC4J 2-15

Creating New Components

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a New Java Program The Object Gallery contains a broad range of icons that represent wizards and builders you can use to create skeletal instances of most of the objects you need to write Java programs. You can use the Object Gallery to create Java applications, Java applets, business components, Web objects and many other types of Java components, as follows: 1. Select File > New. 2. In the Object Gallery, double-click the type of component that you want to create. Double-clicking the object icon will invoke the wizard associated with that type of object. The wizard helps you to create that object within the active project. JDeveloper9i provides a set of sample code that can serve as starting points for a number of types of Java programs: EJB clients and CORBA clients, for example. You can also add your own wizards to the gallery. Instructor Note Demonstrate how to create a new application with a Frame.

Oracle9i JDeveloper: Develop Applications with BC4J 2-16

Code Insight
Lists available methods Displays method arguments

Copyright Oracle Corporation, 2002. All rights reserved.

Code Insight Code Insight assists you when you are writing and editing your Java code, by allowing you to choose from a list of choices. Code Insight allows you to select methods, constants, imports, and method parameters. This feature offers code completion and hints while you are using the content window. As you are typing a class name followed by a period, Code Insight displays a list of the available methods. If you are typing a method, Code Insight offers a list of parameters required by the method. There are a number of options that will help you tune Code Insight to your specific needs or preferences. The options can be set by selecting Preferences from the Tools menu. The Code Insight settings are listed under the Editor node. You can set the speed at which Code Insight will pop up Help text boxes or you can disable Code Insight entirely. Instructor Note Demonstrate Code Insight on the sample application and Frame.

Oracle9i JDeveloper: Develop Applications with BC4J 2-17

CodeCoach
Helps you write more efficient code Helps you optimize use of system resources Can be used for any Java program Provides advice for:
Classes Methods Fields Local variables Memory usage Miscellaneous

Copyright Oracle Corporation, 2002. All rights reserved.

CodeCoach CodeCoach is a utility in JDeveloper9i that helps you write higher quality, better performing Java code. When you run CodeCoach on your Java program, JDeveloper9i looks for code that you can change to improve the performance of your code. It does this by suggesting changes that will help you optimize system resources. You can run CodeCoach on any Java code in your projects, whether you created the code using JDeveloper9i or not. To run CodeCoach, select a Java program, then Select Run > CodeCoach from the menu. The suggestions are written to the message window in the JDeveloper9i IDE.

Oracle9i JDeveloper: Develop Applications with BC4J 2-18

CodeCoach
Checks resource usage for StringBuffer Suggests final for the class

Copyright Oracle Corporation, 2002. All rights reserved.

CodeCoach (continued) For example, if your code appends data to a StringBuffer object too many times, CodeCoach will advise you to change the code.

Oracle9i JDeveloper: Develop Applications with BC4J 2-19

Building and Executing Java Programs


You can use menu items or toolbar buttons: To compile .java files that have changed: Project > Make Project To compile all .java files: Project > Rebuild Project To launch an application: Run > Run
Save Save All Build Debug

Make

Run

Copyright Oracle Corporation, 2002. All rights reserved.

Compiling .java Files into .class Files Before you can run a Java program, you must compile all the .java source files into .class bytecode files. JDeveloper9i provides menu items to build all of the files or just those that have been modified since the last compilation. The following table shows some of the most commonly used menu commands for compiling Java files, together with the equivalent keyboard shortcuts:
Menu Item Project > Make Project Project > Build Project Run > Run Project Debug > Debug Keyboard Shortcut [Ctrl] + [F9] [Alt] + [F9] [F11] [Shift] + [F9] Action Compile the files that have changed since the last compilation. Recompile all the files in the project. Make and run the program. Make and debug the program.

Oracle9i JDeveloper: Develop Applications with BC4J 2-20

Compiling .java Files into .class Files (continued) Running a GUI Application When you run a GUI application, JDeveloper9i launches the application and Java calls the main() method in the application class. This in turn creates an application object and a frame object; the frame object represents the GUI window on the screen. Instructor Note Demonstrate how to build and run a sample application.

Oracle9i JDeveloper: Develop Applications with BC4J 2-21

JDeveloper9i Components
Client Java Middle tier Business Components application Data tier RMI / IIOP HTML JDBC

Servlet HTTP

Copyright Oracle Corporation, 2002. All rights reserved.

JDeveloper9i Features Java Client The Java (fat) client is a Java program that runs on a client machine. HTML Client The HTML (thin) client is run via a browser on a client machine. The HTML is usually dynamically generated by JSP or UIX code on a middle tier and is accessed via a servlet. Oracle Business Components for Java Oracle Business Components for Java is a 100 % Java, XML powered framework that enables productive development, deployment, and customization of multitier database oriented applications from reusable business components. The foundation of the framework comes from the many wizards and productivity tools built in to JDeveloper9i. These wizards produce the software building blocks that manage all of the common facilities required to: Author and test business logic components Reuse business logic through multiple SQL-based views of data Access and update views from servlets, JavaServerPages (JSPs), UIX pages, and Java Swing clients Customize application functionality in layers without requiring modification of the delivered application.
Oracle9i JDeveloper: Develop Applications with BC4J 2-22

JDeveloper9i Features (continued) Oracle Business Components for Java (continued) By eliminating the coding and testing of common application components, Oracle Business Components for Java enable application developers to focus on implementing business solutions.

Oracle9i JDeveloper: Develop Applications with BC4J 2-23

Developing Web Applications

Copyright Oracle Corporation, 2002. All rights reserved.

Web Application Development With JDeveloper9i you can build and deploy server-side Java applications that deliver dynamically generated HTML to any client running a browser. Java Servlets Servlets are portable Java classes that service HTTP requests and dynamically generate HTML. Servlets are portable across platforms and tiers and can be scaled as the needs of your enterprise expand. Servlets are faster than CGI scripts and include integrated support for running in a multithreaded environment. JDeveloper9i provides wizards to create servlets and an integrated servlet engine to test and debug your servlets. JavaServer Pages (JSPs) JavaServer Pages (JSP) technology allows you to embed Java code into an HTML page. It uses HTML tags for the static page content, and JSP tags to embed Java statements to handle the dynamic data content. In this way, it separates the user interface from dynamic content generation, enabling designers to easily change the overall page layout without altering the dynamic content. JSP technology supports a reusable component-based design, making it easier and faster to build Web-based applications.

Oracle9i JDeveloper: Develop Applications with BC4J 2-24

Web Application Development (continued) JavaServer Pages (JSPs) (continued) JDeveloper9i provides a full array of tools for developing, debugging, and deploying JavaServer Pages. JDeveloper9i includes wizards to create JavaServer Pages. The JDeveloper9i Insert Tag Wizard provides an easy way to add custom HTML and Java elements to your code. JDeveloper9i also provides predefined Web-enabled JavaBeans, called Web Beans, and a wizard to create your own. These Web Beans can be reused in JSPs and provide a convenient way to package common HTML generation logic. JDeveloper9i includes a complete JSP Runtime Engine. Thus, JDeveloper9i can quickly launch your JSP for viewing or debugging within the integrated debugger. UIX XML UIX (User Interface XML) technology provides a declarative way to build Web applications where UIX controls can be specified in an XML document and interpreted by a run-time UIX servlet. The UIX HTML controls are a collection of beans that implement the Oracle browser look and feel. These beans generate the HTML to render tabs, buttons, tables, headers, and other layout and navigational components. Working with UIX XML files in JDeveloper means that you can declaratively define a Web application with the UIX components in an XML file using the schema-driven XML editor, and then test and run it. JDeveloper provides wizards to help you build individual UIX XML pages, and UIX template (UIT) files for quicker development, as well as a BC4J UIX application wizard. Additionally, UIX XML supports data binding to any source, not just a Business Components for Java project.

Oracle9i JDeveloper: Develop Applications with BC4J 2-25

Developing Java Client Applications


Bind to BC4J data source Quick to develop using JClient wizards Easy to reuse through XML definitions

Copyright Oracle Corporation, 2002. All rights reserved.

Java-Client Applications In JDeveloper 2, Oracle introduced a series of Swing-based controls which could be bound to data sources. These specialized controls were known as Data-Aware Controls (DAC). DAC was designed to utilize InfoBus which was a standard developed by Sun. InfoBus did not become a popular standard and customers indicated that the benefits of InfoBus were outweighed by the complexity of the controls. JDeveloper9i provides JClient, an improved way of creating Java UIs. JClient is the next generation of Java client for BC4J support in Oracle9i JDeveloper, which works by using a set of customized models based on the JFC/Swing default models. JClient framework consists of models that handle the communication between the client and the business components. The JClient framework and wizards provide: Quick creation wizards that produce databound forms Binding to BC4J data sources supported for any model-based controls, including: - Standard Swing controls - JDeveloper-provided JClient controls - Third party model-based addin controls - Easy reuse of JClient frames and panels supported by XML data definition - Remote methods from BC4J available to Java client due to direct BC4J binding
Oracle9i JDeveloper: Develop Applications with BC4J 2-26

Java-Client Applications (continued) The JClient framework permits developers to build databound Java clients. Instead of relying on JDBC programming, JClient cleanly separates database access code from UI code. Additionally, database access is improved with JClient because its direct binding to BC4J allows it to take advantage of the numerous performance features implemented in BC4J.

Oracle9i JDeveloper: Develop Applications with BC4J 2-27

Developing Enterprise JavaBeans


New Bean creation dialog Wizard driven creation of Enterprise JavaBeans
Stateless Session beans Stateful Session beans Container-managed Entity beans Bean-managed Entity beans

Class editor for creating and modifying:


Fields Methods Events

Copyright Oracle Corporation, 2002. All rights reserved.

Java in the Database With JDeveloper9i, you can easily create Java stored procedures, Enterprise JavaBeans, and CORBA server objects. JDeveloper9i allows you to focus on the business logic, while it takes care of the CORBA and Enterprise JavaBean requirements. Java Stored Procedures You can create, debug, and deploy Java stored procedures with JDeveloper9i. Because Java stored procedures run in the DBMS memory space, complex database functions, as well as repetitive tasks, execute faster than if they were run on the client side. You can access Java stored procedures using SQL statements with standard SQL tools. JDeveloper9i provides an integrated browser for browsing an Oracle database for Oracle8 Objects, Java procedures, and other procedures. Enterprise JavaBeans With JDeveloper9i, you can develop and deploy industry-standard Enterprise JavaBeans (EJBs) to EJB servers, such as Oracle9i. The JDeveloper9i EJB Wizard creates new enterprise Beans or turns existing Java classes into enterprise Beans. The EJB wizard generates the required EJB deployment descriptor, EJB Home interface, and Remote interface for you.
Oracle9i JDeveloper: Develop Applications with BC4J 2-28

Developing JavaBeans
GUI interface for code element changes Add, edit, and delete:
Fields Methods Properties BeanInfo Event sets
JavaBeans

Full set of wizards

Copyright Oracle Corporation, 2002. All rights reserved.

Development with JavaBeans JDeveloper9i includes a full set of GUI-based tools which allow you to make intricate code element changes not only to JavaBeans but to any class. The code that the GUI-based tools manipulate is easy to understand and the generated code, although complex, is error free. With the GUI-based tools, it is easy to add, edit, or delete all of the important elements of any class, including fields, methods, properties, BeanInfo, and event sets. JDeveloper9i provides wizards to help you get JavaBean, BeanInfo, Property Editors, Customizers, and Custom Events started. You can then use the Class Designer to make refinements. The Deployment Wizard makes deploying applications a simple task. The JDeveloper9i Component palette allows you to add all your favorite JavaBeans to any page on the palette. It is also important to note that when you create a JavaBean, JDeveloper9i generates only the class you request and does not generate hidden interfaces or base classes.

Oracle9i JDeveloper: Develop Applications with BC4J 2-29

Database Access
JDeveloper9i IDE provides: Access to multiple database connections Access to database structure and data Integrated SQL Worksheet Connection Editor and Database Browser

Copyright Oracle Corporation, 2002. All rights reserved.

Database Access In most cases, the Oracle Business Components for Java framework provides all the database access functionality you will need. However, JDeveloper9i also provides tools for when you need low-level access to databases. Integrated JDBC For interfacing with the Oracle database, JDeveloper9i provides several JDBC drivers: Oracle Thin JDBC, Oracle-OCI, and Sun ODBC-JDBC Bridge. Integrated SQLJ Translator and Debugger In addition to straight JDBC, JDeveloper9i allows you to use SQLJ programs for low-level database access. A SQLJ program is a Java program containing embedded static SQL statements that comply with the SQLJ language reference syntax. SQLJ statements are translated to standard JDBC statements before normal Java compilation; thus, a proprietary language extension is not introduced. The translator may optionally check the syntax of the SQL code, as well as verify it against the actual database schema, before including it in JDBC calls. SQLJ, an industry standard, guarantees higher code quality by verifying SQL calls at compile time and improves developer productivity by dramatically reducing the number of lines of database code.
Oracle9i JDeveloper: Develop Applications with BC4J 2-30

Database Access (continued) Connection Editor and Database Browser All of JDeveloper9is wizards and deployment tools include a graphical database connection editor that facilitates JDBC driver selection, username and password entries, and browsing of the actual database schema. The generated configuration is converted to JDBC code, and dependent JDBC libraries are automatically imported to the project.`

Oracle9i JDeveloper: Develop Applications with BC4J 2-31

Using JavaDoc

Copyright Oracle Corporation, 2002. All rights reserved.

Using JavaDoc JDeveloper9i provides an easy way to view both Java source and Javadoc from the content window. To view the Javadoc for an element in a program, right-click the element and select Browse Javadoc. This launches another content window to hold the Javadoc of the selected item. To view the source code for an element, right-click the element and select Browse Symbol at Cursor. This launches another content window which contains the source code or a generated stub if the source code is not available. JDeveloper9i uses library information to find and display the source code and Javadoc. To view the source and doc paths for a library, open the Project Settings window, select the Libraries node, and edit the library.

Oracle9i JDeveloper: Develop Applications with BC4J 2-32

Using the Help System

Copyright Oracle Corporation, 2002. All rights reserved.

Getting Help JDeveloper9i is a comprehensive development tool, and it provides many features that you can use to develop Java code more quickly and effectively. The JDeveloper9i Help System To make the best use of the tools, the libraries, and the Java language itself, JDeveloper9i provides a comprehensive Help system that covers all aspects of Java development using JDeveloper9i. You can access Help topics by navigating from the Help page. To start using the Help system, select Help > Help Topics, which launches the Help viewer. From this viewer, double-click a book to see the books and page within the book that you have selected. Click a book or page to view the Help text in the large window in the right portion of the dialog box. Hypertext links help you to navigate within a page or to related pages.

Oracle9i JDeveloper: Develop Applications with BC4J 2-33

Searching the Help System

Copyright Oracle Corporation, 2002. All rights reserved.

Searching the Help System If you are unsure where to look for help on a particular topic, the easiest way to proceed is to click the Index tab at the top of the Help viewer. You can use the Index tab to enter a search string and then search across all available books to find the topic that you have specified. Navigating Between Pages The Help text in the window on the right contains hypertext links to other topics. If you click a hypertext link to view a related topic and then want to go back to the original topic, you can click the Back arrow.

Oracle9i JDeveloper: Develop Applications with BC4J 2-34

Summary
In this lesson, you should have learned how to: Create workspaces and projects Create, build, and execute a simple Java application Access Help topics, source code, and JavaDoc from within JDeveloper9i Use the Structure pane to navigate through a Java program

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 2-35

Practice 2-1 Overview


This practice covers the following topics: Creating a new workspace Creating a new project and application Compiling and running an application Creating a new applet Compiling and running an applet Using JavaDoc from JDeveloper9i

Copyright Oracle Corporation, 2002. All rights reserved.

Practice 2-1 Overview This practice covers the introduction to JDeveloper9i and creating some simple applications.

Oracle9i JDeveloper: Develop Applications with BC4J 2-36

Practice 2-1 1. Start JDeveloper9i and open an existing workspace. a. Select File > Open. b. Select the practice02.jws workspace and click Open. The workspace is in the <JDeveloper>/jdev/mywork/practice02 directory. 2. Create a new project and application. a. Right-click the workspace you just created and select New Project from the context menu. b. From the New Gallery, select Projects > Application Project. c. In Step 1 of the Project Wizard, change the project directory to Hello and the project name to Hello.jpr. You can double-click Project1 to select it, then type Hello. d. In the next step, enter practice02 as the Default Package Name. Accept the default Java Source Path and Output Directory. e. In the next step, accept the default library JDeveloper Runtime. f. Click Finish. The Project Wizard closes and the Application Wizard opens. g. In the Application Wizard, accept the defaults except for the Frame selection. Select Do not add a default frame and click OK. 3. Add some code to your application. a. In the Navigator pane, double-click Application1.java to edit the source code, if the code editor is not already open. b. In the Application1 constructor, enter some code to perform some operations on a String or StringBuffer, and print out the results. You can use the example below. As you enter the code, you can make use of the JDeveloper9i statement completion functionality: - Pause before entering a method name. For example, in the second line of the example, enter sb and then pause. You will see a list of StringBuffer methods, and you can select from this list or continue typing to narrow your selection from the list. - Pause before entering a method parameter. For example, type sb.append. (If you pause, you will see a list of parameter types for the different versions of the append function.) Here is an example you can use: StringBuffer sb = new StringBuffer("Welcome"); sb.append(" to the world"); System.out.println(sb); 4. Compile and run your application. a. Click the Save All button to save your code. b. Click the Make or Build button to compile your application. c. Click the Run button to run your application.

Oracle9i JDeveloper: Develop Applications with BC4J 2-37

Practice 2-1 (continued) 5. Fix compilation errors. a. Add some code to the constructor that contains compilation errors. For example:
String s; System.out.println(s.length())

b. Rebuild or make your project, and fix the compilation errors. 6. View the documentation for a class. a. In your source code, right-click the word StringBuffer and select Browse symbol at cursor from the shortcut menu. The viewer that appears contains the source for the StringBuffer class. If the source is not available in your environment, the viewer will contain generated stubs for the available methods. b. In your source code, right-click StringBuffer again. This time select Browse JavaDoc. If you have time: 7. Create a new applet. a. Right-click the Hello.jpr project and select New from the shortcut menu. b. Select Web Objects > Applet from the New Gallery. c. Accept the defaults and click Can Run Standalone. Click OK. 8. Add some visual components to your applet. a. Edit the applets design: Right-click Applet1.java in the Navigator pane. - Select UI Editor from the shortcut menu. - Change the applets layout manager to XYLayout: - Select this in the Structure pane. - In the property inspector, change the layout property to XYLayout. b. Add a button to the applet. c. Select the Swing from the drop list on the Component palette. - Click the Jbutton icon. Hint: The tool tips indicate the name of each icon. - Click the applet form in the viewer to add the button; drag the edges of the button if you want to resize it. d. Change the button text to YES by editing its Text property in the Property Inspector. e. Add a second button and change its text to NO. f. Add a text field to your applet. Hint: Use the JTextField icon in the Component palette. Make sure that its Text property is blank. Drag the edges of the text field if you want to resize it. 9. Add event handlers to the buttons to make them display text in the text field when a button is clicked. a. Click the Yes button in the viewer. b. Select the Events tab in the Property Inspector.

Oracle9i JDeveloper: Develop Applications with BC4J 2-38

Practice 2-1 (continued) c. Click the space to the right of actionPerformed, and then click the browse () button. This button will create an actionPerformed method in your applet. Accept the default name for the method and click OK. The source code viewer is now displayed, with the new event-handler method highlighted. You can also double-click the button in the design view to create the event-handler method. d. Enter the following line of code on the blank line after the highlighted line: jTextField1.setText("YES!"); e. Go back to the UI Editor and add an event handler to the No button in the same way. Enter the following line of code for the method: jTextField1.setText("NO!"); 10. Run your applet and test your code.

Oracle9i JDeveloper: Develop Applications with BC4J 2-39

Developing a Business Components Application

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 45 minutes 45 minutes 90 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Develop an application using the Business Components Project Wizard Describe the components of the generated application Test the generated application in the Business Component Tester

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson teaches you to create a basic application using the Business Components Project Wizard. In later lessons, you will learn to customize your application.

Oracle JDeveloper9i: Develop Applications with BC4J 3-2

Overview
The steps to create a Business Components application are: 1. Create a database connection. 2. Generate components with the Business Components Project Wizard. 3. Customize your components. The Business Components Project Wizard creates a basic application.

Copyright Oracle Corporation, 2002. All rights reserved.

Overview When you build a new business components application, you should always start by generating components with the Business Components Project Wizard. JDeveloper also provides wizards to add and modify the individual components in a project. It is generally a better idea to create business components using the Business Components Wizard.

Oracle JDeveloper9i: Develop Applications with BC4J 3-3

Creating a Database Connection


The Connection Manager is used to store and access multiple connections. Each connection contains all the information needed to connect to a database. Each connection has a name. Change the connection information to run your application against a different database or schema. You can view schema structure and data from the Connection Manager.

Copyright Oracle Corporation, 2002. All rights reserved.

Storing Database Connection Information Before creating your application, you need a database connection object that your application can use. Your application then accesses the database using a named connection object. Because the details of the connection are not stored in your business components, you can run your application against other databases by changing the connection object. You do not have to alter the business components application.

Oracle JDeveloper9i: Develop Applications with BC4J 3-4

How to Create a New Connection


Right-click the Connections node Select New Database Connection Enter a name and type for the Connection

Copyright Oracle Corporation, 2002. All rights reserved.

How to Create a New Connection To bring up the connection details dialog box: 1. In the navigator window, right-click the Connections folder and select New Database Connection from the Context menu. The slide shows the first group of fields in which you must enter information: Connection Name: Enter the name that you want to give your connection. Connection Type: Select Oracle (JDBC) to connect to an Oracle database, JDBCODBC Bridge to connect to an ODBC data source, Oracle Lite for an Oracle Lite database, or Third Party JDBC Driver if you are supplying the driver. Username and Password: Enter the username and password for your database connection. Role: Enter this information for IIOP connections only. The "Include password in deployment archive" check box: If this box is selected, JDeveloper stores the password, and users are not prompted to enter a password when the application connects to the database.

Oracle JDeveloper9i: Develop Applications with BC4J 3-5

How to Create a New Connection


Complete the connection by entering:
The driver type Hostname JDBC Port Oracle SID

Test the connection

Copyright Oracle Corporation, 2002. All rights reserved.

How to Create a New Connection (continued) Note: Typically, you would select The "Include password" option for development testing purposes only, as it enables you to connect more quickly, and then deselect it again before you deploy your final application. Warning: Once you have finished development and testing of your application, be sure to deselect this option. Because the password is stored in unencrypted text, it could pose a security breach in your final product. The preceding slide shows the remaining fields for a JDBC connection: JDBC Driver: Select a JDBC driver. The choices are: - Oracle JDBC Thin: For client applications or applets - Oracle Lite JDBC: For connecting to an Oracle Lite database - Sun JDBC-ODBC Bridge: For connecting to database other than an Oracle database - Other JDBC: For cases in which you want to use a different driver Host ID, SID, and Port: The host, Oracle instance, and port to which to connect. Finally, you can test your connection by clicking Test Connection.

Oracle JDeveloper9i: Develop Applications with BC4J 3-6

How to Create a New Project Containing Business Components


1. Select the Projects node in the New Gallery 2. Select Project with Business Components

Copyright Oracle Corporation, 2002. All rights reserved.

How to Create a New Project Containing Business Components Create a new project by launching JDevelopers Project Wizard. Select a project containing business components from the Projects node of the New Gallery. When you click Finish in the Project Wizard, the Business Components Project Wizard starts.

Oracle JDeveloper9i: Develop Applications with BC4J 3-7

The Business Components Project Wizard

Step 1: Select the connection.

Step 2: Specify the package. Step 3: Select database objects.

Copyright Oracle Corporation, 2002. All rights reserved.

The Business Components Project Wizard The slide shows an overview of the three steps in the Business Components Project Wizard. In the last step, you select the database objects (tables, views, synonyms, or snapshots) for which you want to create entity objects. For example, if you select the CUSTOMERS and ORDERS tables, JDeveloper will create entities called Customers and Orders. In the last step, you also have the option of creating default view objects and an application module. Instructor Note You could run the Business Components Project Wizard as a demonstration. Select CUSTOMERS and ORDERS, and select the options to generate default view objects and an application module.

Oracle JDeveloper9i: Develop Applications with BC4J 3-8

How to Add Business Components to an Existing Project


Select the Business Components node in the New Gallery

Copyright Oracle Corporation, 2002. All rights reserved.

How to Add Business Components to an Existing Project You can add business components to an existing project by selecting the Business Components node from the New Gallery. Select Business Components which launches the Business Components Wizard. You can also create individual components by selecting the appropriate icon from the New Gallery.

Oracle JDeveloper9i: Develop Applications with BC4J 3-9

What Has JDeveloper Created?


An entity object for each database table An association object for each foreign key constraint A view object corresponding to each entity A view link corresponding to each association An application module containing all views and view links

Copyright Oracle Corporation, 2002. All rights reserved.

What Has JDeveloper Created? The Business Components Project Wizard creates entity objects and associations based on the database objects that you have selected, and it creates view objects and links based on these entities. You can customize any of your components using the component wizards. Example In the database, the CUSTOMERS and ORDERS tables are linked by a foreign key constraint. Create a business components project, selecting the CUSTOMERS and ORDERS tables. Select the options to create default view objects and an application module. JDeveloper creates these components: Two entity objects, Customers and Orders One association, OrdersCustomerIdFkAssoc Two view objects, CustomersView and OrdersView One view link, OrdersCustomerIdFkLink One application module, named after your package Instructor Note If you created a business components project as a demonstration, you can now show the components that JDeveloper has created.
Oracle JDeveloper9i: Develop Applications with BC4J 3-10

Generated Code
A .java file and a .xml file for each entity object and each view object An .xml file for each association object and each view link object A .java file and a .xml file for the application module

Copyright Oracle Corporation, 2002. All rights reserved.

Generated Code Business components are implemented using .java and .xml files. The .xml file contains component metadata; the .java file contains the code that implements and uses the component. Each generated component has a corresponding .xml file which is required by the BC4J run-time environment. Entity objects can have up to three .java files generated and all are optional. By default, one .java file is generated, <Entity>Impl.java, which corresponds to a single instance of the entity. It contains get and set methods for all attributes and associations. You can add code to this file to enforce business logic for entity instances. You can also request to generate the <Entity>DefImpl.java and <Entity>CollImpl.java. The <Entity>DefImpl.java class contains methods that manipulate the entity object as opposed to instances of the entity object. The third class you can generate is the entity collection class. The <Entity>CollImpl.java class represents BC4Js framework cache of the entity rows. View objects can have up to two .java files generated and both are optional. By default, one .java file is generated, the <View>Impl.java file. This file allows you to record class level methods and attributes. However, if you dont need to add any code to this file, you may remove it.

Oracle JDeveloper9i: Develop Applications with BC4J 3-11

Generated Code (continued) You can also request to generate the <View>RowImpl.java file. This file corresponds to a single instance of the view, and contains get and set methods for all attributes and view links. If you dont explicitly need a particular .java file, dont include it in your application. This improves performance.

Oracle JDeveloper9i: Develop Applications with BC4J 3-12

Viewing Information in the Structure Pane


The Structure pane displays the parts that compose the currently selected component. For a view link, the Structure pane displays the view objects connected by the view link. For an entity, the Structure pane displays the entitys attributes and keys.

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle JDeveloper9i: Develop Applications with BC4J 3-13

How to Edit a Business Components Properties


1. Right-click the component in the navigator. 2. Select Edit from the shortcut menu. 3. Make your changes in the components wizard.

Copyright Oracle Corporation, 2002. All rights reserved.

Editing a Business Components Properties JDeveloper provides a wizard for each type of business component. For example, you can use the Entity Object Wizard to create a new entity object or edit an existing one. Each wizard obtains its information from the components .xml file. When you make any changes in the wizard, they are written to the .xml file. You should not edit the .xml file directly.

Oracle JDeveloper9i: Develop Applications with BC4J 3-14

The Business Component Browser


Is a thin Java client application for testing your views and links Creates a form for any component you want to test Allows you to update data and commit transactions Can test local or remote applications

Copyright Oracle Corporation, 2002. All rights reserved.

The Business Component Browser When you have built your application module, you can test it using the Business Component Browser. Using the tester you can test your business logic independently of any user interface code. After the browser is launched, it displays a list of the view objects and view links in your application module. Double-click a component to view it: Double-clicking a view object displays a form containing a field for each attribute in the view object. Double-clicking a view link displays a master-detail form showing both views in the link. Double-clicking multiple components displays tabbed forms. Capabilities of the Browser In the browser, you can browse and update data through any of your view objects. You can view multiple view objects at once and see how changing data in one view affects another. Any rules that you have added to entity objects are enforced, and links between views are automatically coordinated as you scroll through data.

Oracle JDeveloper9i: Develop Applications with BC4J 3-15

Running the Business Component Browser in Local Mode


1. Right-click the application module in the navigator and select Test. 2. Select Local as the middle-tier server type and select Connect. 3. Double-click each view or link that you want to test.

Copyright Oracle Corporation, 2002. All rights reserved.

How to Run the Business Component Browser The Business Component Browser is available from the application module shortcut menu. To run the browser, right-click the application module in the navigator and select Test. You can also use the browser to test application modules that have been deployed to a middle tier or to an Oracle9i database.

Oracle JDeveloper9i: Develop Applications with BC4J 3-16

How to Browse and Update Data in the Browser


Insert a record Delete a record Close the form

Navigate through data

Enter search criteria

Display the form in a separate window

Commit changes

Roll back changes


Copyright Oracle Corporation, 2002. All rights reserved.

Browser Controls There are a number of data controls in the Business Component Browser. The controls are arranged on two separate toolbars: Each window has its own toolbar for browsing and updating data; this is the long toolbar shown on the slide. There is one toolbar for the whole application module that contains the commit and rollback buttons. The Eject Button By default, the browser displays one form at a time; you bring a form to the front of the display by clicking its tab. The Eject button (second from right in the main toolbar) disconnects the form from the main browser, allowing you to arrange multiple forms on your window and view them all at once. When you change data in a view object, other views that include the same entity attributes immediately display the new data. The Commit and Rollback Buttons These buttons commit or roll back all changes in the application module. When you commit, all pending changes are sent to the database by the underlying entity objects.

Oracle JDeveloper9i: Develop Applications with BC4J 3-17

Summary
The Business Components Project Wizard generates all the components of a basic application. It is easier to create a simple Business Components application with the wizard and then edit each component if needed. Use the Business Components Browser to test your business logic before you write the user interface code.

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle JDeveloper9i: Develop Applications with BC4J 3-18

Practice 3-1 Overview


This practice covers the following topics: Creating a new Business Components Project Creating a new JDBC connection Using the Business Components browser

Copyright Oracle Corporation, 2002. All rights reserved.

Practice 3-1 Overview In this practice, you create an application by using the Business Components Project Wizard. Then you test your application by using the Business Components Browser. Instructor Note Provide each student with a database username and password. Students will use this information to set up their connections. In this practice, students are instructed to create a connection. Students do not have to name their connection bc4j; however, the practice solutions all use a connection named bc4j. This means that if students want to run the practice solutions, they either must have a connection named bc4j or modify the solution to use their connection.

Oracle JDeveloper9i: Develop Applications with BC4J 3-19

Practice 3-1 Start JDeveloper9i, and open the practice03.jws workspace. 1. Create a new JDBC connection. a. Expand the Connections node in the JDeveloper Navigator pane. b. Right-click Database and select New Connection from the shortcut menu, which launches the Database Connection Wizard. c. Enter bc4j in the Name field, and select JDBC as the connection type. You can choose any name you want but the practices and examples all use bc4j as the connection name. d. Enter the username and password information for your database, and select Include password in deployment archive. Leave the Role field blank. e. Select the thin JDBC driver. f. Enter the host ID, SID, and port number that was given to you by your instructor. g. Click the Test Connection button to test the connection. h. Click Finish to save the connection. 2. Create a new project containing business components. a. Start the Project Wizard by selecting File > New from the menu or by selecting New Project from the Workspace shortcut menu (right-click the workspace node). b. Select Projects > Project with Business Components from the New Gallery. c. In the Project Wizard, change the last part of the directory name to and the project file name to bc4j. To continue, click Next. d. In the next step, change the Default Package name to bc4j. Accept the remaining defaults e. Click Finish, and the Business Components Project Wizard starts. 3. Create a new business components application. a. In Step 1 of the Business Components Project Wizard, select bc4j as the connection, and then click Next. b. In Step 2, verify that the package name is bc4j, and then click Next. c. In Step 3: i. Select the following tables to create entities:
CUSTOMERS INVENTORIES ORDERS ORDER_ITEMS

ii. Select View Objects and View Links, and select Application Module. iii. Click Next, then Finish. d. Review the Navigator pane to see what JDeveloper has created, and then save all of your files.

Oracle JDeveloper9i: Develop Applications with BC4J 3-20

Practice 3-1 (continued) 4. Test your application. a. In the Navigator pane, right-click your application module (Bc4jModule) and select Test from the shortcut menu. b. In the dialog box, verify that the middle-tier server type is set to Local and the JDBC connection is set to bc4j, and then click Connect. c. In the browser, double-click CustomersView and browse the customers. d. Double-click OrdersView1 and browse the orders. Notice that you can see only the orders for one customer; when you go back to the CustomersView form and navigate to the next record, you see a different set of orders. This is because the applications data model specifies the views in an application as well as how they are linked to each other. e. Close the two open windows. f. Double-click OrdersView, OrderItemsOrderIdFKLink, and OrderItemsView1. Undock each one to make them independent windows. (Note: A slide earlier in this lesson describes the browser buttons and reminds you how to do this.) g. In the OrdersView form, navigate through the orders. Watch the other forms as you do this. Which one changes? Why? h. Navigate through a few rows in the OrderItemsView1 form. Which form changes? Why? i. Use the other forms to navigate through the data, and watch how the data affects each form. j. Close the tester. k. In the Navigator pane, right-click the application module and select Edit. Look at the application modules data model and verify that it defines the way the different forms affect each other in the browser.

Oracle JDeveloper9i: Develop Applications with BC4J 3-21

Implementing Business Rules

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 60 minutes 30 minutes 60 minutes 150 minutes

Topic Lecture Practice 4-1 Practice 4-2 Total

Objectives
After completing this lesson, you should be able to do the following: Create entity objects Change the properties of an entity object Add validation rules and business methods to an entity object Use domain objects to perform complex validation on an entity object

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson covers business components in greater detail. In this lesson, you learn about entity objects: how to create and customize them, and how to use them to manage business logic in your application.

Oracle9i JDeveloper: Develop Applications with BC4J 4-2

Overview
Entity object

Customers Id Name Status Email

Attributes

Status List (Gold Silver Platinum)

Validation rule

CUSTOMERS Database table ID 201 202 NAME Steve Mike STATUS Gold Silver Email msmith@company.com dgonzales@company.com

Copyright Oracle Corporation, 2002. All rights reserved.

Overview Entity objects are the foundation of the Business Components framework. Entity objects contain attributes, business rules and persistence information that applies to a specific part of your business model. Entities are used to define a logical structure of your business, such as product lines, departments, divisions, etc.. They can also define physical items like warehouses, employees, and equipment. For example, Customers is an entity object. An entity object is based on a data source; this one is based on the Customers table. An entitys attributes map to the columns of the data source; the Customers entity has attributes called ID, Name, Status, and Email that map to the corresponding columns of the Customers table. You can attach validation rules to an entity object; the Status attribute has a validation rule that restricts status values to a list of valid values.

Oracle9i JDeveloper: Develop Applications with BC4J 4-3

Entity Object
Represents a database table or other data source Handles all database interaction Contains attributes representing the database columns Encapsulates attribute-level and entity-level validation logic Can contain custom business methods

Customer

Order

Copyright Oracle Corporation, 2002. All rights reserved.

Entity Objects Entity objects are the first components you create when building a business components application. Each entity object represents a business object, or business entity, in your application. Each entity object maps to a data source, usually a database table or database view. Entity objects handle database interaction; all changes to data are cached in the entity object before being committed to the database. Entity objects handle business rules and validation and can contain custom business methods.

Oracle9i JDeveloper: Develop Applications with BC4J 4-4

Two Ways to Create an Entity Object


Select the Business Components node in the New Gallery, then select Entity Object. Right-click the package name in the navigator and select New Entity Object.

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a New Business Component There are two ways of creating a new entity object. The procedure is the same for adding any new business component to your package, including: Entity objects Domains Associations View objects View links Application module After you have followed the steps outlined in the preceding slide, the Entity Object Wizard is displayed. Follow the steps in the wizard to create the new component. Instructor Note To avoid repetition, the procedure for creating other types of components is not described in as much detail in the following lessons. The procedure is essentially the same as is shown here.

Oracle9i JDeveloper: Develop Applications with BC4J 4-5

The Entity Object Wizard


Enter a name.

Select a database object.

Move to the next step.

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a New Business Component (continued) The simplest way to create a new entity object is to use the Entity Object Wizard: 1. Enter a name for your entity object. 2. Select a database object (for example, a table) on which to base your entity object. 3. Accept all the defaults in subsequent steps, and then click Finish to save your entity object. You can then go back and edit your entity object, if you need to. Instructor Note When you create a business component, it is generally easiest to go through the minimum number of steps required by the wizard, save your component, and exit the wizard. You can then edit your component; this time the wizard is displayed with tabs, making it easier to decide what you want to change.

Oracle9i JDeveloper: Develop Applications with BC4J 4-6

Files Generated for the Customers Entity Object


Customers.xml: Metadata
The Entity Object Wizard obtains all of its information from this file

CustomersImpl.java: Entity object class


Extends the EntityImpl class Row level Includes getter and setter methods for attributes

CustomersDefImpl.java: Entity definition class


Extends the EntityDefImpl class Contains run-time metadata describing the entity object Describes all instances of the entity
Copyright Oracle Corporation, 2002. All rights reserved.

Files Generated for the Customers Entity Object When you create a business components application using the Business Component Project Wizard, JDeveloper generates two files for each entity: Entity.xml (for example, Customers.xml). This file contains metadata for your business component. EntityImpl.java (for example, CustomersImpl.java). This is the entity object class, containing getter and setter methods for each attribute in your entity. This file is generated by default, but you can remove the class from the Entity Object Wizard.

Oracle9i JDeveloper: Develop Applications with BC4J 4-7

Files Generated for the Customers Entity Object (continued) In addition, from the Entity Object Wizard, you can generate one more file: EntityDefImpl.java (for example, CustomersDefImpl.java). This is the entity definition class. It describes all instances of the entity. A client can call methods to find information about the entity such as attribute names and types, database source, and so on. EntityCollImpl.java (for example, CustomersCollImpl.java). This class is used to cache entity rows. It is not necessary to override any methods in this class. Instructor Note Probably the easiest way to understand the purpose of the .xml file is to think of it as the place where the wizard gets all of its information. That information includes the names and types of all the attributes. Students do not modify the entity definition class in any of the practices.

Oracle9i JDeveloper: Develop Applications with BC4J 4-8

The Supporting Java Classes

EntityImpl
The entity class Represents a row of data Provides getter and setter methods

EntityDefImpl
The entity definition class Represents the whole entity Can be used to modify the entity definition

EntityCollImpl
Represents the cached set of rows from the entity It is not necessary to modify or override this class

Copyright Oracle Corporation, 2002. All rights reserved.

The Java Classes There are two primary Java classes that are used to implement entity objects. These classes provide methods to manipulate either row-level data or the definition of the entity itself. You use these classes to add custom validation of retrieval logic or even to dynamically add validation rules at run time. Both of these classes can be generated from the Entity Object Wizard in JDeveloper. EntityImpl This is the entity object class. At run time, one entity object is instantiated for each row of data. This class contains methods to get and set entity attribute values. All entity object classes extend this class. EntityImpl provides methods to insert, update, delete, and lock rows. The BC4J framework uses this class to manage instances of each entity. Unless you need to override standard behavior, you don't even need an entity. EntityDefImpl This is the entity definition class. At run time, one entity definition is instantiated for each entity. You can add methods to this class that are used by all entity object instances. EntityCollImpl This class represents the set of rows from the entity stored in the internal BC4J cache. You do not need to generate or modify this class.
Oracle9i JDeveloper: Develop Applications with BC4J 4-9

Assigning an Initial Value to an Entity Attribute


Add code to the create() method in EntityImpl.java.

Select the Create method check box to generate a create() method.

create() runs automatically when the entity is instantiated.


Copyright Oracle Corporation, 2002. All rights reserved.

Assigning an Initial Value to an Entity Attribute The create() method Entity objects have a create() method that is called automatically by the business components framework when the entity is instantiated. You can override the default create() method of EntityImpl.java to populate attributes with initial values. This is particularly useful when the values are complex or require a calculation based on other data or information. To get the create() method in your EntityImpl.java file, double-click the entity and in the wizard, go to the Java tab. In the Generate Methods section, check the Create Method check box and click OK. The create() method will be added to the EntityImpl.java file. Add your custom logic after the call to super.create(). Turning Off Code Generation Options in the Wizards After Modifying the Code If you clear a code-generation option while you are in the wizard, that code is deleted from your entity, even if you have modified it. For this reason, you should be careful when modifying the options in the Java tabbed page of the Entity Object Wizard. Static Initial Value: Initial Value property If the initial value you want to assign is static, you can use the default value field on the attribute settings tab of the Entity wizard. This technique is easier but less flexible. Use this technique if the value is static and won't change over time.
Oracle9i JDeveloper: Develop Applications with BC4J 4-10

Mapping an Attribute to a Database Sequence


create or replace trigger insert_ord_id BEFORE INSERT ON orders FOR EACH ROW DECLARE new_id number; BEGIN SELECT orders_seq.NextVal INTO new_id from Dual; :new.order_id := new_id; END;

1. Create a database trigger.

2. Set the attribute type to DBSequence.

Copyright Oracle Corporation, 2002. All rights reserved.

Mapping an Attribute to a Database Sequence In many cases, you may want to use a database-supplied sequence number as an attribute or key of an entity. You would use a sequence where you want a unique number that is generally sequential but may have an occasional gap in the sequence. Some examples would be the ID of and Order, a Product ID, an Employee ID, etc. Having a trigger to manage this sequencing will ensure that no matter where the data comes from, the column will always be populated using the database sequence. There are two steps to setting an attribute to use a database sequence in JDeveloper. First, you must create a database trigger that will populate the column with the value on the insert of a new record. Having a trigger manage this insures that all rows inserted into the table will use the sequence. After you have created the trigger, select DBSequence as the attribute type for the attribute that will be populated by the sequence. JDeveloper and the BC4J framework handle populating the attribute and refreshing the value on the client after the row is inserted.

Oracle9i JDeveloper: Develop Applications with BC4J 4-11

Practice 4-1 Overview


This practice covers the following topics: Initializing an attribute to a default value Assigning a database sequence to an attribute

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 4-12

Practice 4-1 Start JDeveloper9i and open the workspace Practice04.jws. 1. Create a new project containing business components. a. Start the Project Wizard by selecting File > New from the menu or by selecting New Project from the Workspace context menu (right-click the workspace node). b. Select Projects > Project with Business Components from the New Gallery. c. In the Project Wizard, change the last part of the directory name to and the project file name to entities. To continue, click Next. d. In the next step, change the default package name to entities. e. Click Finish, and the Business Components Project Wizard starts. 2. Create a new business components application. a. In Step 1 of the Business Components Project Wizard, select bc4j as the connection, and then click Next. b. In Step 2, verify that the package name is entities, and then click Next. c. In Step 3: i. Select the following tables to create entities:
CUSTOMERS INVENTORIES ORDERS ORDER_ITEMS

ii. Select View Objects and View Links, and select Application Module. iii. Click Next, then Finish. d. Review the Navigator pane to see what JDeveloper has created, and then save all of your files. 3. Use the database sequence orders_seq to populate the order_id attribute of the Orders entity. a. Edit the Orders entity b. Change the orderId attribute to use the orders_seq for its value. Hint: Refer the the slide "Mapping an Attribute to a Database Sequence" if you need a reminder of how to do this. The ORDERS table has a database trigger that uses the sequence to populate the ORDER_ID column. c. Save your changes, rebuild your application, and then test your application using the Business Components Browser. d. In the Browser, open the OrdersCustomerIdFkLink form. e. Add a new Order to a Customer. You won't need to assign an OrderId because it will now be retrieved from the database sequence. The only required fields are the OrderDate and the CustomerId. If you choose to complete the other fields, use the existing order rows for sample data. f. Commit the transaction and requery the Customers to see that the sequence number was committed to the database. g. Close the Browser. 4. Use the database trigger on the order_items table to populate the LineItemId attribute. a. Follow the same steps you followed for step 3 only against the OrderItems entity. b. Test your changes by adding a line item to any order. Note: ProductId must be valid and unique within an Order.
Oracle9i JDeveloper: Develop Applications with BC4J 4-13

Validating Attributes
Use validation rules to validate an entity attribute. Use the Entity Object Wizard to add and edit rules. The Entity Object Wizard provides different types of rules:
Compare a single value Compare with a list of valid values either hard coded or the results of a SQL query Compare against a minimum, maximum, or range of values Validate using a custom method

Validation is XML based

Copyright Oracle Corporation, 2002. All rights reserved.

Validation Rules You can add a validation rule to an entity attribute by selecting the Validation tab in the Entity Object Wizard. There are several types of validation rules, allowing you to validate your attribute against a single value, a list of valid values, or a minimum, maximum, or range of values; alternatively, you can write a method to specify your own validation rules. The validation rules are stored in XML, so you can modify the rules at runtime if required.

Oracle9i JDeveloper: Develop Applications with BC4J 4-14

ListValidator: Example
Specify a list of values for Customers.Status.

Customers.xml

Copyright Oracle Corporation, 2002. All rights reserved.

Validation Rule: Example The preceding slide shows an example of a ListValidator type of validation rule. This rule stipulates that any value entered for a Customers status must be a member of a list of valid values. In this example, the list contains literal values (Gold, Silver, and Platinum); you can retrieve your list of valid values from a SQL query or a view object attribute. Instructor Note The preceding slide shows a very simple example. One of the problems with this rule is that it is strict about case: gold would be rejected as invalid. Students might also mention that they would like the list of valid values to be dynamic. The practice for this lesson requires them to create a more sophisticated version of this validation rule.

Oracle9i JDeveloper: Develop Applications with BC4J 4-15

Using the Custom MethodValidator for an Attribute


Calls a Java method in your entity object Custom validation methods must:
Be defined as public Accept a single argument of the same type as the attribute Return a Boolean value
public boolean validateNlsLanguage(String value) { if( // add your validation code ) return true; else return false; }

Copyright Oracle Corporation, 2002. All rights reserved.

Using the Custom MethodValidator The MethodValidator allows you to create a custom method that can be used to validate any attribute within an entity. It is useful if the validation is complex or if it applies to more than one attribute within and entity. The method must be defined as public, accept a single argument of the same type as the attribute, and return a Boolean value. The candidate method name must start with the keyword validate. The code can be as complex or simple as the validation rules require.

Oracle9i JDeveloper: Develop Applications with BC4J 4-16

Using the Custom MethodValidator for an Entity


Calls a Java method in your entity object Custom validation methods must:
Be defined as public Return a Boolean value Be named as validateXXX
public boolean validateOrder() { if( // add your validation code ) return true; else return false; }

Copyright Oracle Corporation, 2002. All rights reserved.

Using the Custom MethodValidator for an Entity The MethodValidator also allows you to create a custom method that can be used to perform entity validation that is not specific to a single attribute. The method must be defined as public and return a Boolean value. The name of the method must begin with the keyword validate. The code can be as complex or simple as the validation rules require.

Oracle9i JDeveloper: Develop Applications with BC4J 4-17

Adding Custom Attribute Validation


EntityImpl.java contains typesafe methods to get and set each of the entitys attributes. Add custom validation code in these methods. Call setAttributeInternal() to set the attribute value after your validation code.
public void setCreditLimit(Number value) { // add your custom code here setAttributeInternal(CREDITLIMIT, value); }

Copyright Oracle Corporation, 2002. All rights reserved.

Adding Custom Validation for an Attribute The Entity Object wizard creates an EntityImpl class by default for each entity. This class includes predefined methods to get or set attributes within the entity. The BC4J framework defines these methods and generates skeleton code in the EntityImpl class. You can then add code to implement any required custom validation logic. The default setter method contains a call to setAttributeInternal(). This is the method that sets the attribute value in the entity object. You call this method if the attribute value passes your custom validation code. Your code should go before the call to setAttributeInternal(). For example, you could add custom validation to the creditLimit attribute that checks that the value is less than some predetermined limit. This limit can be based on anything you want. In the example below, it is a simple arbitrary value. The limit could also be calculated based on your specific business rules. public void setCreditLimit(Number value) { int MAX_VAL = 10000; if (value.intValue() > (MAX_VAL)) { throw new JboException( "Credit Limit Exceeds Maximum Value"); } // the generated call to setAttributeInternal() follows setAttributeInternal(CREDITLIMIT, value); }
Oracle9i JDeveloper: Develop Applications with BC4J 4-18

Overriding EntityImpl Methods

You can also add validation by overriding many of the methods inherited from EntityImpl.java. For example: validateEntity() doDML() beforeCommit()

Copyright Oracle Corporation, 2002. All rights reserved.

Overriding EntityImpl Methods To override a method inherited from EntityImpl.java, select your <entity>Impl.java file in the navigator. Then, select Tools > Override Methods, expand oracle.jbo.server.EntityImpl and check the method(s) you want to override. validateEntity() method This method is used for complex logic that applies to more than one attribute in the instance. doDML() method This method fires after all of the attribute and entity validation is complete. You can add code that is beyond validation logic here. For example, you could add code that records audit information in another entity. beforeCommit() method This method is used for rules that involve more than one instance of the same entity of more than one entity. Since any of the instances could have changed in the current transaction, it is important to delay validation until all of the instances been posted.

Oracle9i JDeveloper: Develop Applications with BC4J 4-19

Domains
Use domains for more complex validation:
Format of a phone number Validity of a URL Validity of an e-mail address Checksum of digits of a credit card number

Validation is done by the domain constructor. A domain is not bound to a particular entity or attribute. You can use domains to validate multiple attributes across multiple entity objects.

Copyright Oracle Corporation, 2002. All rights reserved.

Domains A domain is not bound to a particular entity or attribute. For example, if you create a domain to validate phone numbers, you can use your domain to validate any attribute that is a phone number: customers phone number, suppliers phone number, and so on. You can also use domains to validate the attributes of a view object.

Oracle9i JDeveloper: Develop Applications with BC4J 4-20

Domains: Example
The URLDomain verifies that an attribute is a valid URL. The validate() method is called by the domains constructor. WebURL.java
protected void validate() { try { // Make sure the user entered a valid URL java.net.URL u = new java.net.URL(mData); } catch (java.net.MalformedURLException e) {throw new oracle.jbo.domain.DomainValidationException ("Invalid URL"); }

Copyright Oracle Corporation, 2002. All rights reserved.

Domains: Example When you create a domain object, you are essentially creating a new data type; the example creates a new type called URLDomain. You can then change an entity attributes type to your new type; in this example, you could change the type of the Web site attribute to URLDomain. When the entity is instantiated, or the Web site attribute is populated or changed the URLDomain() constructor is called. The constructor executes the validation code that you have written to verify that this attribute is valid. Note: Domain validation code is executed whenever you query existing data. If existing data might fail the check, you need to either correct the existing data, or code the check so that existing data is determined to be valid.

Oracle9i JDeveloper: Develop Applications with BC4J 4-21

How to Create and Use the URLDomain


1. Create the domain URLDomain 2. Add validation code to the validate() method in WebURL.java. 3. Edit the ProductInformation entity and change the type of the CatalogURL attribute to URLDomain.

URLDomain appears in the list of types.

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Domain The slide shows the steps to create and use the URLDomain domain. When you create a new domain object, JDeveloper generates code in the domains constructor to call the validate() method. Therefore, if you add your validation code to the validate() method, it will automatically be executed when the domain object is instantiated. In the final step, you change the type of the Web site attribute to URLDomain . This causes the validation code to be called when the entity object is instantiated.

Oracle9i JDeveloper: Develop Applications with BC4J 4-22

Where To Put Validation


There are a number of places you can put validation: Predefined validators: For simple XML-based rules Custom MethodValidators: For more complex attribute and entity rules Attribute setter method: For complex attribute rules Override EntityImpl.java methods: For more complex entity rules and custom behaviors Domains: Can be used for multiple attributes across multiple entity objects

Copyright Oracle Corporation, 2002. All rights reserved.

Where To Put Validation So far, you have examined three places that support validation of attribute values. They are the predefined validators, the generated attribute setter methods, and domains. Predefined Validators The predefined validators are XML based and can be manipulated easily at run time. This makes them flexible but they are limited to simple validation rules. These validators are called during the execution of the setAttributeInternal() method. They also throw a ValidationException automatically if the attribute fails the validation. Custom MethodValidators You can define both attribute and entity custom method validators, which allows for flexible coding. Attribute Setter Method Adding validation codes to the setter methods allows you to code quite complex validation logic. You can also add code that is beyond validation to the method. For example, you could add code that manipulates other attributes based on the current attribute value.

Oracle9i JDeveloper: Develop Applications with BC4J 4-23

Where To Put Validation (continued) Domains Domain validation is most useful when there are multiple attributes requiring the same validation rules. Domains can validate any attribute in any entity. For example you could create a URLDomain that checks that the attribute contains a valid URL. This domain could then be assigned to all attributes that contain a URL. Other Methods There are a number of other methods that each entity inherits from EntityImpl.java. You can override any of these methods as needed and add validation logic.

Oracle9i JDeveloper: Develop Applications with BC4J 4-24

Validation Order
Attribute validation occurs in the following order: Domain validation: On instantiation of an entity object Setter method: On creation or modification of an attribute Predefined validators: On a call to setAttributeInternal() Attribute MethodValidators validateEntity() method Entity MethodValidators doDML() method beforeCommit() method
Copyright Oracle Corporation, 2002. All rights reserved.

Validation Order Attributes can be validated in any combination of the techniques that have been covered in this lesson. The validators are called in the following order: Domain validation: This happens each time an entity object is instantiated, or the attribute is changed. Setter method: This happens when an attribute is populated for the first time, or modified. Predefined validators: The validators are executed automatically when you call setAttributeInternal(). Attribute MethodValidators validateEntity() method Entity MethodValidators doDML() method beforeCommit() method Note: If logic in the doDML() method changes any of the attributes on the current instance, the validateEntity() method is fired again before posting the data.

Oracle9i JDeveloper: Develop Applications with BC4J 4-25

Summary
In this lesson, you should have learned how to: Create an entity object Generate Java code for an entity object Validate an entity attribute using a validation rule or a domain object Add custom code to the entity object to validate attribute values

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 4-26

Practice 4-2 Overview


This practice covers the following topics: Adding a validation rule to an entity object Validating an entity attribute using a domain object Adding business rules to an entity object

Copyright Oracle Corporation, 2002. All rights reserved.

Instructor Note In step 4, the students add code to calculate a discount for 10 or more items. They will place the discount value in the discountUnitPrice column. The column name implies that this is the new unit price, but for this practice it is just a simple discount value. In the next practice they will calculate a true discountUnitPrice based on a percentage discount and the base unit price.

Oracle9i JDeveloper: Develop Applications with BC4J 4-27

Practice 4-2 To start this practice: Start JDeveloper, open the Practice04.jws workspace, and open the project that you created in Practice 4-1. 1. Add a Validation Rule to Validate Customers Status a. Edit the Customers entity and add a validation rule. b. Your new rule is a ListValidator rule that ensures that the Status attribute has one of the following values:
Platinum Gold Silver

c. Save your changes and run your application module in the Business Component Browser. d. In the browser, open CustomersView. Change the Status attribute to an invalid value (such as Premium) and press [Enter] or [Tab]. This will trigger the validation rule and an Exception dialog box will appear. e. Click the rollback button to undo your change, and change the Status attribute to a valid value. This time your change is accepted. f. Close the Business Component Browser. 2. Change Your Validation Rule to be Case Insensitive You may have noticed that your validation rule rejects values such as silver, which are invalid only because the case is different. a. Change your validation rule so that it accepts any combination of uppercase and lowercase letters. Hints: - You must add some code in CustomersImpl.java. - If you cannot remember the exact name of a method you want to call in your code, type the object name followed by the ., and wait for a second; JDeveloper will bring up a list of methods to select from. b. Save and rebuild your code, and test your changes in the Business Component Browser. Note The solution to step 2 involves adding code to CustomersImpl.setStatus(). Two possible solutions are: In the Entity Object Wizard, enter the list of valid values in uppercase (PLATINUM, GOLD, SILVER); in setStatus(), convert the status to uppercase. In the Entity Object Wizard, leave the list of valid values as Platinum, Gold, Silver; in setStatus(), convert the initial character of the status to uppercase and the rest of the word to lowercase. Note that when you change the status in setStatus(), the new value immediately appears on the form in the tester. If you prefer to see values in initial capped format, you will probably prefer the second solution.

Oracle9i JDeveloper: Develop Applications with BC4J 4-28

Practice 4-2 (continued) 3. Validate Email Attributes Using a Domain Object a. Create a domain object called EmailAddressDomain that verifies that an attribute is a valid e-mail address. Use the slides that discuss domains earlier in this lesson to remind yourself how to do this. If it checks an attribute and finds an invalid e-mail address, your domain should do the following: throw new oracle.jbo.domain.DomainValidationException ("Invalid Email Address"); Note: If you need help with the code, there is a code snippet at the end of the practice. b. Edit the Customers entity and set the type of its Email attribute to EmailAddressDomain. c. Save your changes and test them in the browser. Try changing the e-mail addresses of a Customer to invalid values and to valid values. 4. Set a Discount for Multiple Quantities a. Add code to OrderItemsImpl.java to enforce the following business rule: We offer a $5 discount on quantities of ten or more on all items. (The discount attribute contains values in dollars.) Note that if there are less than 10 items, the discount should be set to zero. Hint: Add code to OrderItemsImpl.setQuantity() that sets the discount. b. Test your changes in the browser. Open OrderItemsOrderIdFkLink and insert some line items. Enter a quantity of 10 or more, and then tab out of the quantity column and verify that a discount is entered in the discountUnitPrice column. Insert a row with a quantity of less than 10, and verify that no discount is set. Email Address Validation Code Snippet
int atpos = mData.indexOf('@'); int dotpos = mData.lastIndexOf('.'); int lastchar = mData.length() - 1; // Check for conditions that indicate an invalid email address if (atpos == -1 || dotpos == -1 || // there is no "@" or "." atpos == 0 || // string begins with "@" mData.lastIndexOf('@') != atpos || // string contains more than // one "@" mData.indexOf(' ') != -1 || // string contains a space mData.indexOf(',') != -1 || // string contains a comma dotpos < atpos || // there is no "." after the // "@" dotpos == atpos + 1 || // "." immediately follows "@" dotpos == lastchar ) // string ends with "." { throw new oracle.jbo.domain.DomainValidationException ("Invalid email address"); }

Oracle9i JDeveloper: Develop Applications with BC4J 4-29

Using Entity Associations in Business Logic

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 45 minutes 60 minutes 105 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Create entity associations Traverse entity associations Use associations in business logic

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson explains how to create and use entity associations in business logic.

Oracle9i JDeveloper: Develop Applications with BC4J 5-2

Associations
Define a relationship between entity objects Facilitate access to data in related entity objects May be based on database constraints May be independent of database constraints Consist of a source (master) and a destination (detail) entity

Copyright Oracle Corporation, 2002. All rights reserved.

Associations JDeveloper automatically creates associations between entities that represent tables that are joined by a foreign key constraint. Associations are like master-detail relationships in a relational database. You can create an association as follows: 1. Right-click the package name. 2. Select Create Association from the Context menu. This displays the Association Wizard. Viewing the Components of an Association When you select an association in the Navigator pane, the Structure pane displays the following information about the association: The source (master) entity and entity attributes The destination (detail) entity and entity attributes Generated Files JDeveloper generates only one file for each association: Association.xml (for example, OrderPlacedBy.xml), which contains all the metadata for the association.

Oracle9i JDeveloper: Develop Applications with BC4J 5-3

Association Example
A Customer can place Orders An Order is placed by a Customer

OrderPlacedBy Customers Source Association Orders Destination

Copyright Oracle Corporation, 2002. All rights reserved.

Association Example In this example, the Customers entity is the source in the association. The Order entity is the destination in the association. That means that each Customer can be the source of multiple Orders, and that every Order is owned by a Customer.

Oracle9i JDeveloper: Develop Applications with BC4J 5-4

Accessor Methods
Optional methods created by the Association Wizard Provide access to data from the associated entity Are bi-directional For Example:
Get all Orders for a Customer Get Customer information from an Order

Copyright Oracle Corporation, 2002. All rights reserved.

Association Accessor Methods Association Accessor methods are used to traverse the association from source to destination and from destination to source. Traversing an association provides access to data from the opposite end of the association. For example, suppose you have two entities with an association. The entities are Customers and Orders. From the Customers entity, you can traverse the association to get access to the Orders that belong to that Customer. The reverse is also true. You can access the Customers information from the Order by traversing the association.

Oracle9i JDeveloper: Develop Applications with BC4J 5-5

Association Types
Association
Entities are related but not completely dependent Either end of the association can exist without the other Usually a categorization

Composition
Destination entity is completely dependent on the source entity The source entity owns the destination entity No destination entity can be created without the owning entity existing first

Copyright Oracle Corporation, 2002. All rights reserved.

Types of Associations Association: An association is a relationship between to entities that are not completely dependent on each other. Each end of the association may exist without the other. This type of association is usually a categorization of some type of business entity. For example, a customer may be categorized by a customer type. Composition: A composition relationship means that the source entity owns the destination entity object. The destination entity object cannot exist without the owning entity object existing first. The source entity object is a container for the destination entity object. For example, an order owns the order lines associated with it. Compositions and Validation When a change is made to the destination entity, a validate message is sent to the source entity. When this happens, the source entitys validate() method is called when the transaction is committed.

Oracle9i JDeveloper: Develop Applications with BC4J 5-6

Deciding the Association Type


Two questions to ask: Can a destination entity object exist without the source?
If yes, the source is associated to the destination. If no, the source is composed of the destination.

When I delete the source, do I delete the destination?


If yes, the relationship is a composition. If no, the relationship is an association.

Copyright Oracle Corporation, 2002. All rights reserved.

Deciding the Type of Association Order and LineItem are related by a composition: An order cannot be deleted until all its line items are deleted. When a line item is changed, a validate message is sent to the parent order. Composition In a composition relationship, the source (master) is marked for validation anytime a destination (detail) entity object is changed. For example, if a LineItem is changed, the Order will be revalidated. You could add code to the validateEntity method in the source that would check all of the children for compliance to any business rules you need to apply.

Oracle9i JDeveloper: Develop Applications with BC4J 5-7

Creating Entity Associations

The Many side of the association

The One side of the association

Copyright Oracle Corporation, 2002. All rights reserved.

Creating Entity Associations Entity associations define a relationship between two entity objects based on common attributes. The relationship can be one-to-one or one-to-many; you can use two one-to-many associations to implement a many-to-many relationship. The association allows entity objects to access the data of other entity objects through a persistent reference. Although the same type of relationship can also exist at the table level through a foreign-key relationship or object reference, an entity object only needs an association to access the data of another entity object. You can create associations regardless of whether the database has the corresponding referential integrity constraints. An example of a relationship is a one-to-many association between employees and departments; they might have a relationship where the Dept entity object has a Deptno attribute that is related to the Deptno attribute of the Emp entity object. To create an association, right-click the business component package and select Create Entity Association from the Context menu. Use the Association Entities window to choose which entity object represents the source (master) entity object and which represents the destination (detail) entity object. The source entity object selection typically represents the entity containing the primary key of a foreign key constraint. Once an association is defined, the entity objects can use the association to traverse transparently to the other side of the association in a predefined manner. For example, the employees of a department might be accessed through a department by issuing the call deptImpl.getEmps().
Oracle9i JDeveloper: Develop Applications with BC4J 5-8

Creating Entity Associations

Copyright Oracle Corporation, 2002. All rights reserved.

Creating Entity Associations (continued) Use the Attributes window to choose the attributes that define the relationship between the source and destination entity objects of an association. The Attributes window appears twice, once for the attributes of the source entity and once for the attributes of the destination entity. At least one attribute must be selected for each entity object in order to create a valid association; the resulting detail must match each pair of selected attributes. Entity name: The name of the source or destination entity object chosen in the previous Association Entities panel. Available attributes: A list of the entity object's available attributes. You can select these attributes by clicking the attribute and then clicking the right arrow. Press [Ctrl] and click to select more than one attribute. Available keys: Select an available key and click the right arrow to add the attributes that define the key to the Selected Attributes pane. While you can explicitly choose the attributes used for the relationship, there may be keys that already exist that have the set of attributes selected. If so, you can save time by selecting an available key from this list. Another advantage of using a key is that if you select a key on the source entity object, the matching key (if applicable) is included by default on the destination side.
Oracle9i JDeveloper: Develop Applications with BC4J 5-9

Creating Entity Associations

Copyright Oracle Corporation, 2002. All rights reserved.

Creating Entity Associations (continued) Selected Attributes: The attributes you have selected as either source or destination attributes. Remove attributes from this list by clicking an attribute and then clicking the left arrow. Control-click to select more than one attribute. The Association Properties window controls many of the behavioral aspects of the association such as the association cardinality and the exposure of the association accessors. This panel has divisions on the left and the right for the source and destination sides of the association. Cardinality: Cardinality is used to define the relationship between objects by setting the minimum and maximum number of members that may participate in the association. Select the cardinality from the drop-down list: 0...1 Indicates that a single value is allowed, but is not required 1 Indicates exactly one value is required * Indicates there many values are allowed, but none are required 1..* Indicates at least one value is required, but many are allowed

Oracle9i JDeveloper: Develop Applications with BC4J 5-10

Creating Entity Associations (continued) Expose Accessor: By default, associations are exposed in the owning entity objects through association accessors. These accessors are a special kind of attribute that return the data from the other side of an association. Select this check box to expose the accessor method. Leaving this check box cleared prevents the accessor from being inserted into the owning entity object. Accessor: Enter the name of the accessor method or accept the default name provided. The accessor method is available to the entity object on the other side of the association, meaning that in a Dept-Emp association, Dept has an accessor called getEmp(). Use Database Key Constraints: Select this check box to create entity-level key constraints when generating tables. Associations in the middle tier represent key constraint relationships in the database tier. Associations can be used solely in the middle tier, or they can be pushed down to the database as well. If you select this option, the appropriate database key constraint objects are created to correctly represent the association settings you have selected. If you subsequently select Create Database Objects (right-click your package in the Navigation pane), the appropriate database constraints will be constructed for you. Composite Association: A composition is an association in which the source object owns the destination object. You might think of the source object as a container for the destination objects. For inserts, updates and deletes, the destination entity object is considered part of the parent entity object. Setting this option also enables validation of the master entity object, as well as the detail entity object, if a detail entity object is modified. A master entity object containing valid detail entity objects cannot be deleted until all the contained detail entity objects are deleted. When you attempt to change a detail entity object, you must successfully lock the owning master entity object or the change is not allowed.

Oracle9i JDeveloper: Develop Applications with BC4J 5-11

Traversing Associations: Source to Destination


Order getLineItem() ItemOrderedOnAssoc LineItem

The source entitys EntityImpl.java file contains a method to get the destination entity. For example, OrdImpl.java contains the method:
public oracle.jbo.RowIterator getLineItem()

Use the methods of RowIterator to step from row to row and get individual attribute values.

Copyright Oracle Corporation, 2002. All rights reserved.

Traversing Associations: Source to Destination Traversing an association from source to destination is more complicated, because you must handle multiple destination entities for each source entity. Source-to-destination accessor methods use the oracle.jbo.RowIterator object to navigate through the destination entities. JDevelopers online help contains the full javadoc for oracle.jbo.RowIterator. Example of Source-to-Destination Accessor Methods JDeveloper generates one accessor method in Ord.java: public oracle.jbo.RowIterator getLineItem(). There is no corresponding setter method. This code segment identifies all of the line items in order and gets the quantity of each: RowIterator lineItems = getLineItem(); LineItemImpl lineItem; // Get the next line item while ((lineItem = (LineItemImpl) lineItems.next()) != null) { // Get the Quantity from lineItem double qtyAsDouble = lineItem.getQuantity().doubleValue(); ... }
Oracle9i JDeveloper: Develop Applications with BC4J 5-12

Traversing Associations: Destination to Source


Order getLineItem() ItemOrderedOnAssoc LineItem getTrackingNo()

The destination entitys EntityImpl.java file contains methods to get and set the source entity. For example, LineItemImpl.java contains getOrd() and setOrd(). You could add a method to LineItemImpl.java to get the tracking number of the order containing this item:
public String getTrackingNo() { return getOrd().getTrackingNo(); }

Copyright Oracle Corporation, 2002. All rights reserved.

Traversing Associations: Destination to Source By default, JDeveloper generates two pairs of accessor methods for each association: one pair for traversing the association in each direction. These accessor methods are generated in the entity object classes on either end of the association. Example of Accessor Methods The entities Ord and LineItem are linked by the association ItemOrderedOnAssoc. JDeveloper generates two methods in LineItemImpl.java (the destination entity object) for traversing the association from destination to source: public OrdImpl LineItemImpl.getOrd(): Get the order to which this line item belongs. public void LineItemImpl.setOrd(OrdImpl value): Set the value of the order to which this line item belongs. To retrieve information from the source entity while in the destination entity, use the get<Source>() method plus the get method for the attribute that you want to retrieve. Example: In the LineItemImpl.java file, add a method to get the associated orders tracking number. public String getTrackingNo() { return getOrder().getTrackingNo(); } Instructor Note You can change the names of the accessor methods in the Association Wizard.
Oracle9i JDeveloper: Develop Applications with BC4J 5-13

Summary
In this lesson, you should have learned how to: Create entity associations Traverse associations in both directions Use associations in business logic

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 5-14

Practice 5-1 Overview


This practice covers using associations in creating business logic.

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 5-15

Practice 5-1 To begin this practice, start JDeveloper9i, open the Practice05.jws workspace. 1. Create a new project containing business components. a. In the Project Wizard, change the last part of the directory name and the project file name to associations. To continue, click Next. b. In the next step, change the default package name to associations. c. Click Finish, and the Business Components Project Wizard starts. 2. Create a new business components application. a. In step 1 of the Business Components Project Wizard, select bc4j as the connection, and then click Next. b. In step 2, verify that the package name is associations, and then click Next. c. In step 3: i. Select the following tables to create entities:
CUSTOMERS INVENTORIES ORDERS ORDER_ITEMS PRODUCT_INFORMATION

ii. Select View Objects and View Links, and select Application Module. iii. Click Next, then Finish. 3. In the previous practice, you added code to calculate a discount based on the number of items ordered. The discount was a flat $5, which is not very realistic. In this practice, you will add a discount calculation that is based on the price of the item. a. Add a discount calculation that applies a 10% discount on line items where 10 or more items are ordered. If there are more than 30 items ordered, apply a 15% discount. Get the listPrice from the ProductInformation entity. Set the unitPrice attribute to the listPrice and set the discountUnitPrice attribute to the discounted unitPrice. For example if the listPrice is $100 and the customer orders 20, the discountUnitPrice attribute should be 90. If the order 30 the discountUnitPrice should be 85. Hint: Use variables for the discount percentages. b. Build and test your project. 4. In addition to the quantity-based discount, you must apply a special discount based on the status of the customer. a. If a customer is Platinum, apply an additional 5% discount. This discount is in addition to any quantity discount you have already applied. b. If a customer is Gold, apply an additional 3% discount. This discount is in addition to any quantity discount you have already applied. c. Build and test your project.

Oracle9i JDeveloper: Develop Applications with BC4J 5-16

Creating and Managing Database Objects

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 60 minutes 60 minutes 120 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Create an entity without an underlying database table Create entity associations Create a database table from an entity definition Create an entity constraint

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson covers generating database objects from entity objects. It also covers creating entity associations and constraints.

Oracle9i JDeveloper: Develop Applications with BC4J 6-2

Forward Engineering
JDeveloper can create database objects from business components:
Create a database table from the definition of an entity object Create a database constraint from an entity constraint

Generating database objects from business components is known as forward engineering.

Copyright Oracle Corporation, 2002. All rights reserved.

Forward Engineering In previous lessons, you learned how to create entity objects based on a database tables. You can also do the opposite: that is, create a database table based on an entity object. This procedure is called forward engineering.

Oracle9i JDeveloper: Develop Applications with BC4J 6-3

Creating an Entity Without an Underlying Database Object


Create a new entity by using the Entity Object Wizard. Do not select a database object for the entity. Click New in the Attributes tabbed page. Enter information for each attribute and for the database column that is to be created.
Copyright Oracle Corporation, 2002. All rights reserved.

How to Create an Entity without an Underlying Database Object When you create a new entity object, you do not have to select a data source. If you do not select a data source, you must add all of your entity attributes explicitly. The procedure for creating an entity without a data source is as follows: 1. In the Navigator pane, right-click the package and select Create Entity Object. 2. In step 1 of the Entity Object Wizard, enter the name of the new entity. 3. Click Next without selecting a database object. 4. In step 2 of the wizard, click New to add a new attribute. 5. In the New Entity Attribute dialog box, enter the name and type of your attribute. You must also enter a name and type for the database column. These values will be used later, when you generate the database table. Click OK to save your new attributes. 6. Continue adding attributes to your entity. You must designate at least one attribute as a primary key, by selecting the Primary Key option in the New Entity Attribute dialog box. 7. In step 3 of the wizard, you can edit the settings of any of your attributes. Click Finish to close the wizard. The next page describes the options and fields in the New Entity Attribute dialog box.

Oracle9i JDeveloper: Develop Applications with BC4J 6-4

Defining a New Entity Attribute

Copyright Oracle Corporation, 2002. All rights reserved.

New Entity Attribute Dialog Box Use the Define New Entity Attribute dialog box to add a new attribute to the entity object and to edit its settings. Select the Java data type and any additional settings for this attribute. Attribute Value Name: A valid Java identifier name which is also unique among all other attributes of this entity object. The accessor methods for the attribute will be known by this name. Type: The data type of the object. This could be be one of the given types or any Java value-holder class name such as java.math.BigDecimal. If a domain is selected as the Java data type, then this attribute should respect the domain's settings: it can only restrict those settings further. Default: Provide a default value for this attribute. When a new row is created, this attribute initially gets this default value at run time. Persistent: This check box is displayed if this attribute is mapped to a column in a database table. Selecting the Persistent check box enables the Database Column group box to allow you to enter enter column settings for the forward generation of tables from entity object definitions.

Oracle9i JDeveloper: Develop Applications with BC4J 6-5

New Entity Attribute Dialog Box (continued) Attribute Value (continued) Discriminator: A discriminator attribute makes your view object's result set polymorphic: that is, the result set can contain different types of objects, and the client can process the result set without having to know about the different types of objects. Primary Key: Select this check box if this attribute is a part of or is a primary key for the entity object. At least one attribute in an entity object must be defined as a primary key attribute. This attribute will become the table's primary key if you forward engineer the entity. Mandatory: When this check box is selected, each row must have a non-null value for the selected attribute or the row is not valid. Updateable Always: When this option is selected, the selected attribute may be updated. While New: When this option is selected, the attribute can be updated only when it is part of a new, uncommitted row: the attribute can only be updated before it is written to a database object. Never: When this option is selected, the selected attribute may not be updated using the framework. For example, you can use this setting for attributes whose values are populated in the database through triggers. Refresh After Update: Select this check box if this attribute should have its values refreshed after the row containing that attribute is posted to the database. This property is typically selected for those attributes whose values are modified inside the database through some database procedures or triggers and the framework needs to reload the data for that attribute when the relative row is posted to the database. Insert: Select this option for those attributes whose value is generated by the database when a new row is posted into it: for example, Sequence numbers. You can use this feature to assign primary key values from a sequence in a database trigger. Database Column These settings are used for the forward generation of new tables from an entity object and for hints to a UI client regarding the attributes database properties. Name: The name of the database column to which this attribute is mapped. Type: The column type in the database to which this attribute is mapped. The column type information also shows precision and scale information for numeric types and length for string types. This precision and scale is enforced by the framework at run time. Queriable: When this check box is selected, the selected attribute can participate in a query condition. If the column to which this attributes is mapped can be part of a query filter (a WHERE clause), then this property should be set selected. For example, this property should be selected for NUMBER column types, but not set for BLOB types.

Oracle9i JDeveloper: Develop Applications with BC4J 6-6

New Entity Attribute Dialog Box (continued) Database Column (continued) Unique: When this check box is selected, there can be at most one row where the selected attribute has any given value. If this property is added to an attribute, the appropriate database constraint is created, along with the database object in the Create Database Objects operation from the shortcut menu (right-click the package in the Navigation pane). Change Indicator: When this check box is selected, the selected attribute becomes a time-stamp field that contains the date on which that row was last updated. Only one attribute in an entity object may have this property.

Oracle9i JDeveloper: Develop Applications with BC4J 6-7

Creating the Entity

Copyright Oracle Corporation, 2002. All rights reserved.

Creating the Entity The last step in defining a new entity object is to select which Java classes JDeveloper9i will create. You can edit these classes to customize the entity objects behavior. This page provides options that let you generate classes (that is, *Impl classes) for the entity object and the entity definition. Generate an entity definition class for the entity definition if you want to customize its methods. Generate an entity object class for the entity object if you want to customize their attribute getter and setter methods, or other methods from the entity object class. This is the typical place to add custom validation code. By default, the wizard generates the entity object class, but not the entity definition class. You can also generate an entity collection class. This class is used internally by BC4J to interact with the entity cache. It is not necessary to create or override methods in this class.

Oracle9i JDeveloper: Develop Applications with BC4J 6-8

Creating the Entity (continued) Entity Definition Class Generate Java file: When you select this check box, JDeveloper generates a Java file that you can edit to customize the entity object definition's behavior. Otherwise, JDeveloper generates only an XML file. The Generate Java file property is selected when custom create and find methods are required for an entity type. The entity definition class is a single class at run time, and it is a good choice to add such custom methods. Also select this option to provide custom properties to the entity definition and entity attribute definitions at run time through the APIs. If an entity publishes or subscribes to an event through the Publish and Subscribe tabbed pages, this check box is automatically set because most of the event code is generated in the definition files. Entity Collection Class Generate Java file: When you select this check box, JDeveloper9i generates a Java file that you can use to override methods used to interact with the entity cache. It is not necessary to generate this class or override its methods. Entity Object Class Generate Java file: When you select this check box, JDeveloper generates a Java file you can edit to customize the entity object's behavior. Otherwise, JDeveloper generates only an XML file. This property is typically set to implement custom validation logic for the entity in its Validate Entity method or for entity attributes in the setter methods for the attributes. Generate Methods: When entity objects are created, accessor methods are automatically generated by default. Data manipulation, create, and remove methods are not generated. Accessors: When you select this check box, JDeveloper adds accessor methods (for example, getJob and setJob) to the entity objects generated Java file. These accessor methods provide type-safe access to the corresponding attribute fields. They also provide a place to add your own custom code for validation. Data Manipulation Methods: When you select this check box, JDeveloper adds data manipulation methods to the entity objects generated Java file. These data manipulation methods are lock(), which you can modify to customize the entity objects locking behavior, and doDML(), which you can modify to customize its update, insert, and delete logic. The lock() method is called by the framework whenever an entitys row in the database is locked for modifications. The doDML() method is called by the framework with appropriate DML command to insert, update, or delete the row corresponding to the entity instance during the Transaction-Commit cycle. This method can be overridden to modify the update behavior. For example, instead of directly updating by a SQL statement as the framework does, perform an update by a procedure call to the database. Validate Method: Select this check box to generate a validate method where you can customize the entity objects validation logic.

Oracle9i JDeveloper: Develop Applications with BC4J 6-9

Creating the Entity (continued) Entity Object Class (continued) Create Method: When you select this check box, JDeveloper adds a create method to the entity objects generated Java file. You can modify the create method to customize or add additional initialization features to the entity objects create logic. Remove Method: When you select this check box, JDeveloper adds a remove method to the entity objects generated Java file. You can modify the remove method to customize or add clean-up code to the entity objects remove logic. Extends: Typically, in an applications organization, the framework supplied by JDeveloper is customized by a core group and all entity objects for the organization must be built over this customized framework. Click Extends to open the Framework Base Classes dialog box to select a base class.

Oracle9i JDeveloper: Develop Applications with BC4J 6-10

Creating a Database Table from the Definition of an Entity Object


Right-click the package name in the Navigator pane and select Create Database Objects. Select the tables that you want to create. If a table of the same name exists, the data will be lost.
Package name (read only) Entity objects Table you want to create
Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Database Table from the Definition of an Entity Object JDeveloper generates a table for each entity object that you select, whether the table already exists or not. If you re-create a table that already exists, the existing table is dropped and any data is lost. Use the Create Database Objects dialog box to add a new database object to the database. It is assumed you already created an entity object (in the Navigation pane, right-click your package and select Create Entity Object from the shortcut menu). Note: To create foreign keys, both the source and destination entities involved in the association must be inserted into the Objects to Create list. Warning: Be sure to archive existing data before creating new tables so that you can restore it, if necessary. You must drop any existing database objects that have the same name as those used in the new database tables and key constraints. If there is data in an identically named existing table, it will be lost if you proceed. A message box warns you of this beforehand. Name: This field is not editable; it reminds you of the package you are using. Database Object: This is a list of the entities in the current package. Each entity object has information about the database object it represents. This database information is used to determine the object to create. Objects to Create: The selected objects that will be created when you click OK.
Oracle9i JDeveloper: Develop Applications with BC4J 6-11

About Entity Constraints


An Entity Constraint:
Represents a key constraint in the database Is defined in terms of entity objects and attributes Is only used during forward generation

The Entity Constraint Wizard creates:


Primary key constraints Unique key constraints Check integrity constraints Foreign key constraints

An entity constraint does not apply until you create a database object based on the constraint.

Copyright Oracle Corporation, 2002. All rights reserved.

About Entity Constraints Forward engineering also includes the ability to create a database constraint based on an entity constraint. You create an entity constraint using the Entity Constraint Wizard. Entity constraints are usually derived from entity associations. Constraints are optional and are used only in forward generation of database objects. When you create an entity and select an attribute as a primary key, the wizard creates a unique constraint for the entity. It does not automatically create a primary key constraint for that entity. However, if you choose to forward engineer that entity into a database table, the database will create a primary key constraint and JDeveloper9i will show that constraint in the structure of the entity. This constraint creation is automatic. If you have an association between two entities, it will not automatically become a foreign key constraint, even if you forward engineer the entities. Foreign key constraints must be created either manually or by selecting Use Database Key Constraints in the association wizard. This gives you complete control over using database level foreign key constraints.

Oracle9i JDeveloper: Develop Applications with BC4J 6-12

Creating an Entity Constraint


Right-click the entity name in the Navigator pane and select Create Entity Constraint. Run the Entity Constraint Wizard:
Step 1: Enter the constraint name and the name to be used in the database. Step 2: Select the attributes of the constraint. Step 3: Select the constraint type and validation options.

Entity constraints are displayed in the Structure pane.

Copyright Oracle Corporation, 2002. All rights reserved.

Foreign Key Constraints When creating a foreign key constraint, you must enter a value for the reference. Enter the database name of the primary or unique key that the foreign key references. To display database constraints use the SQL statement select * from user_constraints; from a SQL worksheet. Instructor Note You may want to conduct a quick review with the students about when to apply check constraints and for what they are best suited.

Oracle9i JDeveloper: Develop Applications with BC4J 6-13

Creating a Database Constraint from the Definition of an Entity Constraint


Right-click the package name in the Navigator pane and select Create Database Objects. Select the entity with the constraint and click OK. If the table already exists, any data in it will be lost.
Create tables and constraints for these entities.

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Database Constraint When you create database objects using the Create Database Objects dialog box, JDeveloper generates database constraints for any entity object constraints that you have created.

Oracle9i JDeveloper: Develop Applications with BC4J 6-14

Managing Schema Changes


JDeveloper9i : Provides database synchronization Checks the business logic tier against the database Reports differences Allows you to decide which side (BC4J or the database) is correct

Copyright Oracle Corporation, 2002. All rights reserved.

Managing Schema Changes JDeveloper9i provides a utility that checks the business logic tier against a database schema. It verifies that the definitions of the entities and associations are consistent with those in the associated database. If they are not the same, the synchronization utility reports the differences and allows you to choose which differences you want to change.

Oracle9i JDeveloper: Develop Applications with BC4J 6-15

Managing Schema Changes

Copyright Oracle Corporation, 2002. All rights reserved.

Managing Schema Changes In this example, the CustomerGeoLocation column has been dropped from the CUSTOMERS table. The synchronization utility checked for differences between the entity definition and the table definition. It found that the CustomerGeoLocation column is missing from the table. It then proposes that you set the attribute to transient. Database Table New column Missing column Business Logic Tier No corresponding attribute A corresponding persistent attribute in an entity object, or in a domain A persistent attribute doesn't have the same settings No corresponding key constraint Key constraint present Action Add the missing attribute For an entity object, make the attribute transient. For a domain, delete the attribute Change the attribute settings. Add the missing key constraint to metadata.. Remove key constraint.

Changed type, precision, or scale Key constraint added Key constraint removed

Oracle9i JDeveloper: Develop Applications with BC4J 6-16

Summary
In this lesson, you should have learned how to: Create an entity without an underlying database table Create entity associations Create a database table from an entity definition Create an entity constraint Synchronize the business logic tier and the database

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 6-17

Practice 6-1 Overview


This practice covers the following topics: Creating a new entity object Creating a new entity constraint Creating a database table from the definition of an entity object Synchronizing Business Components with database objects

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 6-18

Practice 6-1 Start JDeveloper9i, and open the practice06.jws workspace. 1. Create a database object from an entity object. a. Select the NewEntity project in the Navigator pane. b. Think of a new entity to add to the online orders business model. One possibility is to add an entity called Accessories that could be used to look up suggested additional purchases for a particular inventory item. For example, if a customer orders a mobile phone, an application could use this entity to list a case, spare battery, and so on that the customer might want to order. c. Create your new entity using the Entity Wizard; do not base your entity on a database table. d. If your entity links to an existing entity in the model, create a foreign key constraint to define the relationship between your new entity and an existing entity. Create an association corresponding to the foreign key constraint. Hint: When creating a foreign key constraint, enter the database name of the referenced primary key in the References field. 2. Create the components needed to use your new entity. a. Create a default view based on your new entity. b. Create an association between your new entity and the source of its foreign key. c. Create database objects based on your new entity. d. Create a link between the new view and the source view for the link. e. Modify the data model of your application module to include the new view object and new link. f. Save your changes, and test your application using the Business Component Browser. Insert some data into your new database table. Test the foreign key constraint by inserting into your view object, using both valid and invalid values for the Join column. 3. Synchronize your Business Components with changing database objects. a. Make a change to your database schema that you can synchronize to. Open a SQL worksheet by right-clicking the bc4j connection and selecting SQL Worksheet. Enter and run the following SQL statement. alter table customers drop column cust_geo_location; b. Run the synchronize utility to see the differences between your project and the current state of the database. c. Synchronize the Customers entity with the customers database object. d. Edit the CustomersView view and remove the CustGeoLocation attribute. e. Build and test your project.

Oracle9i JDeveloper: Develop Applications with BC4J 6-19

Presenting Business Data

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 45 minutes 75 minutes 120 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Describe the role of view objects in the business components framework Create view objects Customize view objects using the View Object Wizard Define relationships between view objects Add calculated attributes to view objects Use Polymorphic Rowsets in view objects

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson describes the role of view objects in a BC4J application. You will learn how to create and customize view objects to meet your specific application requirements. You will also learn how to define and use relationships between view objects. In addition, this lesson teaches how to add nonpersistent calculated attributes to view objects and how to build and use polymorphic rowsets with view objects.

Oracle9i JDeveloper: Develop Applications with BC4J 7-2

Overview
Entity object Customers ID Name Status Web site View object CustomerStatus select name and status from customers Name order-by name Mike Steve Susan

Status Silver Gold Platinum

ID 201 202

NAME Steve Mike

STATUS Gold Silver

WEBSITE http://www... http://www... Database table

Copyright Oracle Corporation, 2002. All rights reserved.

Overview The first part of building a Business Components application concerns designing and building the business logic into the application. After you design and test the application, you must focus on how to present the data in a useful and logical way. There can be any number of ways you may want to look at the data in your application. Each different way, whether it is a subset of the attributes or a subset of rows, can be expressed with a view object. The slide shows an example of a view object, called CustomerStatus. A view object is bound to an entity object; this one is based on the Customers entity object. A view objects attributes map to the attributes of the underlying entity object; the CustomerStatus view object has attributes that map to the Name and Status attributes of the underlying entity object. A view uses a SQL query to sort and filter data. Instructor Note Students may be confused by two apparently conflicting pieces of information: A view object attribute is bound to an entity attribute. A view object gets its data from a SQL query. The relationship between views, entities, and the database is explained on the next several pages.
Oracle9i JDeveloper: Develop Applications with BC4J 7-3

View Objects
Present a view or slice of business data Are used for joining, filtering, projecting, and sorting your business data Can be based on any number of entity objects Can also be constructed from a SQL statement
PriorityOrder CustomerStatus

Order

Customers

Copyright Oracle Corporation, 2002. All rights reserved.

View Objects You can think of a view object as representing a database query. The diagram shows two view objects: one based on a single entity object, and one based on two entity objects.

Oracle9i JDeveloper: Develop Applications with BC4J 7-4

Interaction Between Views and Entities: Retrieving Data


The view object queries the database directly. Data retrieved by the query is saved to the entity objects cache.
EO VO

getAttr()

Non-persistent attributes are stored and retrieved from the view object's cache
VO

getCalcAttr()
Copyright Oracle Corporation, 2002. All rights reserved.

Interaction Between Views and Entities: Retrieving Data A view object gets its data by using a SQL query, and a view object is bound to an entity object. This slide should help to explain these two apparently conflicting pieces of information. View objects and entity objects work together when a view object retrieves data: The view object queries the database, ensuring that its data is current. Data retrieved by the query is saved to the entity objects cache and then sent to the view object.0 The following slide shows the interaction between views and entities when updating data. Calculated Attributes A calculated attribute is based only on a database query, not on an entity object attribute. Calculated attributes get their data directly from a column expression in the SQL query; the data is stored in the view objects cache. Entity Objects The data is passed to the entity object to validate business rules stored in the object. The view object determines what data is retrieved. The entity object guarantees that the data follows the defined business rules. This has one very important implication: you cannot even query data that does not satisfy the business logic recorded in the Entity Objects.
Oracle9i JDeveloper: Develop Applications with BC4J 7-5

Interaction Between Views and Entities: Updating Data


The view object updates the entity objects cache. The entity object updates the database.
EO setAttr() VO

Copyright Oracle Corporation, 2002. All rights reserved.

Interaction Between Views and Entities: Updating Data When you update data in the database, the process described on the previous slide is not quite reversed: The view updates the entity objects cache. When the transaction is committed, the entity object updates the database. As stated on the preceding page, the entity object guarantees the validity of the data that is being committed to the database.

Oracle9i JDeveloper: Develop Applications with BC4J 7-6

Synchronization of View Objects


When an application module is run, multiple views that reference the same entity stay synchronized.

Order status is changed in one view New value is immediately displayed in other views based on same entity
Copyright Oracle Corporation, 2002. All rights reserved.

Synchronization of Views Generally, a view does not receive data from an entity until the view asks for it. However, if you are running an application module and looking at two views that reference the same entity, the data in the views is synchronized automatically. This happens only if two views in the same application module instance are accessing the same row of data. Instructor Note This feature is easy to demonstrate using the Business Component Browser. 1. Build a new BC4J application that is based on the course schema. 2. Use the Business Components browser to test an application module 3. In the browser, double-click OrderPlacedByLink, and then double-click OrdView. 4. Click the Eject button to display the forms in separate windows, and arrange the forms so that you can see both of them at once. 5. Change the orders status in one of the forms, and then tab out of the status field. The status is changed in the second form. Note that this will not happen if you run the browser twice and view each form in a different instance of the browser.
Oracle9i JDeveloper: Develop Applications with BC4J 7-7

Creating a View Object Using the View Object Wizard

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a View Object 1. Right-click the package name in the Navigator pane and select Create View Object from the shortcut menu. The View Object Wizard opens. 2. (Optional) In step 1 of the View Object Wizard, enter a name for your view. 3. While you are still in step 1 of the wizard, select one or more entities on which your view will be based, and use the right-arrow button to move your selections to the Selected list. The example on the slide creates a view based on the Customers entity. Click Next. 4. In step 2 of the wizard, select one or more entity attributes to include in your view. Click Finish. You can then go back and edit your view object, if you need to.

Oracle9i JDeveloper: Develop Applications with BC4J 7-8

Classes Related to View Objects in oracle.jbo.server


ViewObjectImpl
This is the view object class. It represents a view object. Use this class to add or override behaviors that apply to the view object

ViewRowImpl
This is the view row class. It represents a row in a view object. Use this class to add or override behaviors that apply to a row within the view object.

Copyright Oracle Corporation, 2002. All rights reserved.

Classes Related to View Objects in the oracle.jbo.server Package The preceding slide shows two of the classes that you use when writing code to customize view objects: ViewObjectImpl and ViewRowImpl. Both classes are in the oracle.jbo.server package. ViewObjectImpl This is the view object class. At run time, one view object is instantiated for each view object. This class contains methods that apply to the whole view object. For example: setWhereClause(): Set the where clause of the SQL query findByKey(): Find all rows in the view that match a given key first(), last(), next(): Navigate through the rows in the view objects set of rows ViewRowImpl This is the view row class. At run time, one view row is instantiated for each row in the view. This class contains methods to get and set view attribute values. You would use this class to override or add methods that a client would call for a specific row. For example, you could add a method that returns a concatenation of the First and Last Name of a Customer.

Oracle9i JDeveloper: Develop Applications with BC4J 7-9

Files Generated for the LineItemView View Object


LineItemViewImpl.java: The view class
Extends ViewObjectImpl Generation is optional

LineItemViewRowImpl.java: The view row class


Extends ViewRowImpl Generation is optional

LineItemView.xml: Metadata
Always generated The View Object Wizard gets all its information from this file

Copyright Oracle Corporation, 2002. All rights reserved.

Files Generated for the LineItemView View Object When you create a business components application using the Business Component Project Wizard, JDeveloper generates two files for each view object: View.xml (for example, LineItemView.xml). This file contains metadata for your business component. ViewImpl.java (for example, LineItemViewImpl.java). This is the view object class. This file is generated by default, but you can remove the class from the View Object Wizard. In addition, from the View Object Wizard, you can generate one more file: ViewRowImpl.java (for example, LineItemViewRowImpl.java). This is the view row class. The generated file contains getter and setter methods for each attribute in your view object. For example, LineItemViewRowImpl contains the methods getQuantity() and setQuantity(), to get and set the Quantity attribute.

Oracle9i JDeveloper: Develop Applications with BC4J 7-10

Example of a View Object


PriorityOrder View Object SELECT Cust.ID, Cust.FIRSTNAME, Cust.LASTNAME, Cust.STATUS Ord.ID, Ord.ORDERDATE, Ord.STATUS FROM CUSTOMERS Cust, ORDERS Ord Cust.ID = Ord.CUSTOMER_ID AND Cust.status = 'Platinum' ORDER BY Ord.ORDERDATE Customers ID FirstName LastName Status Email Orders ID Orderdate Status Custid Trackingno

Copyright Oracle Corporation, 2002. All rights reserved.

Example of a View Object The example shows the PriorityOrder view object, where a priority order is an order from a Platinum customer. Recall that a view object: Specifies columns Filters records Specifies row order Can be updated View Objects and Master-Detail Queries Although a view object can query multiple tables, you should not use a single view object to represent a master-multiple detail relationship. Instead, create two view objects and join them with a link. (Links are described later in this lesson.)

Oracle9i JDeveloper: Develop Applications with BC4J 7-11

Practice 7-1 Overview


This practice covers creating and editing a new view object.
Select entity Select objects attributes Edit the query

Copyright Oracle Corporation, 2002. All rights reserved.

Practice 7-1 Create the PriorityOrderView object. Look at the previous slide to remind yourself what this view object looks like. To start the practice, you must open workspace practice07.jws and project Views.jpr. 1. Create a new view object PriorityOrderView based on the Customers entity. 2. Select the CustomerId, CustFirstName, CustLastName, and Status attributes in the Customers entity, and click Finish. 3. Edit PriorityOrderView so that it reflects the following definition: - Add Orders to the entities list. - Add the following attributes to the list of selected attributes. OrderId Orderdate OrderStatus - Edit the Where clause so that the query returns only the rows where the status of the customer Platinum. 4. Add PriorityOrderView to your application modules data model. 5. Build, save, and test your application.
Oracle9i JDeveloper: Develop Applications with BC4J 7-12

Calculated Attributes in Views


You can add attributes based on calculated fields and function calls. Click New in the Attributes tabbed page of the View Object Editor.
Name: Type: Alias: Expression: LineTotal Number LINE_TOTAL quantity* unitDiscountPrice

Copyright Oracle Corporation, 2002. All rights reserved.

Calculated Attributes View object attributes do not have to be based on entity attributes; they can be based on SQL expressions. The slide shows a calculated attribute called LineTotal, which is based on the values of the QUANTITY, PRICE, and DISCOUNT columns in the database. You must check the Selected in Query checkbox to be able to enter an Expression. If your view includes more than one entity object, the Expression must use the entity alias when referring to attributes with ambiguous names. Instructor Note The expression that you define for a calculated attribute sets the attributes value when the view objects SQL query is executed. It does not force the attribute to be recalculated when other attributes are changed. For example, if an end user changes the discount on an item, you would want the line total to be recalculated automatically. To do this, you must add code to the view row object. Students go through this exercise in Practice 7-2.

Oracle9i JDeveloper: Develop Applications with BC4J 7-13

View Links
A view link is an active link between view objects. You can create view links by providing the following:
Source and destination views Source and destination attributes

InventoryItem Source view object

OrderForItem Link

LineItem Destination view object

Copyright Oracle Corporation, 2002. All rights reserved.

View Links View objects are joined by view links. You can create a view link as follows: 1. Right-click the package name. 2. Select Create View Link from the Context menu. This displays the View Link Wizard. Viewing the Components of a View Link When you select a view link in the Navigator pane, the Structure pane displays the following information about the view link: The source (master) view and view attributes The destination (detail) view and view attributes Generated Files JDeveloper generates only one file for each view link: <ViewLink>.xml (for example, OrderForItem.xml), which contains metadata used by the View Link Wizard.

Oracle9i JDeveloper: Develop Applications with BC4J 7-14

Master-Detail Views
Different types of master-detail relationships are supported.

Master to single detail

Master to multiple details

Cascading masterdetail to any depth

Copyright Oracle Corporation, 2002. All rights reserved.

Master-Detail Views You can use view links to create master to multiple detail and cascading master-detail relationships between view objects.

Oracle9i JDeveloper: Develop Applications with BC4J 7-15

Traversing Links
Links may be traversed in either direction. ViewRowImpl.java contains a method to get the associated row iterator. For example, OrdersViewRowImpl contains the method:
public oracle.jbo.RowIterator getOrderItemsView ()

Use the methods of RowIterator to move from row to row and get individual attribute values.

Copyright Oracle Corporation, 2002. All rights reserved.

Traversing Links Traversing a view link is similar to traversing an association: you use the accessor method in the source (master) view object to get the RowIterator object that contains all the associated rows in the destination (detail) view object. You can also traverse a view link from destination (detail) to source (master). Similar to the example above, the OrdersViewRowImpl class contains a method to return a single row containing the OrdersView. Using this method, you can determine and manipulate detail information about the Order to which the current OrderItem belongs.

Oracle9i JDeveloper: Develop Applications with BC4J 7-16

Polymorphism
The ability to process objects differently depending on their class or data type A fundamental concept in Java
Animal name play() eat()

Dog name play() bark()

Cat name play() meow()

Copyright Oracle Corporation, 2002. All rights reserved.

Polymorphism Review In object-oriented programming, polymorphism refers to a programming languages ability to process objects differently depending on their class or data type. This ability is key to Javas extensible and dynamic capabilities. In the example, there are three classes: Animal, Dog, and Cat. The Dog and Cat classes inherit all of the attributes and methods of the Animal class. They can override those methods or implement new methods of their own. Polymorphism enables Java to know which play() method to invoke based on the type of object. If the object is a Cat object, the Cat play() method will be called, if the object is a Dog object, the Dog play() method will be called. Consider the following code. Animal animal = new Dog(); animal.play(); Which play() method will be called? Java will call the Dog.play() method because the animal object is really a Dog object. Remember that Java is a late-binding language. That means that it binds, or chooses, which method to call at run time, not at compile time. Java waits until run time to check the real object type and then calls the correct method. JDeveloper9i provides the ability for you to map different types of entity objects or view objects to the same rowset. This allows you to create clients that process a single rowset that contains multiple types of objects.
Oracle9i JDeveloper: Develop Applications with BC4J 7-17

Implementing Polymorphic Rowsets


Employee name email phone empType getName() getEmail()

HourlyEmployee hourlyRate empType calculatePay()

SalariedEmployee salary commissionPct empType calculatePay()

Copyright Oracle Corporation, 2002. All rights reserved.

Implementing Polymorphic Rowsets To implement a polymorphic rowset, you must create both Entity objects and a View object. The next few pages describe how to create a polymorphic rowset using JDeveloper9i. Creating the Entity Objects JDeveloper9i provides the ability to map multiple entity types to a single rowset. In this example, we have the Employee entity which has been extended twice, once for HourlyEmlployee and once for SalariedEmployee. Both HourlyEmployee and SalariedEmployee implement a method calculatePay() which calculates the pay based on different criteria. For the HourlyEmployee, the calculation is the hourlyRate * 40. The calculation for the SalariedEmployee is the base salary + commission, if there is any. Each entity also has a different set of attributes. HourlyEmployee has an hourlyRate whereas SalariedEmployee has salary and commissionPct. Of course, both SalariedEmployee and HourlyEmployee inherit all the attributes and methods of Employee. Discriminator Attribute There is also an empType attribute in all three entities. This attribute is used by BC4J as a discriminator attribute. It helps define which employees are hourly and which are salaried. In the HourlyEmployee Entity, empType will have an initial value = H, whereas in the SalariedEmployee Entity, empType will have an initial value = S.
Oracle9i JDeveloper: Develop Applications with BC4J 7-18

Creating HourlyEmployee
Create an HourlyEmployee entity using the Entity Object Wizard. Extend the Employee entity. Include attributes for hourlyRate and empType. Set the default for empType to H.
HourlyEmployee hourlyRate empType calculatePay()

Copyright Oracle Corporation, 2002. All rights reserved.

Creating HourlyEmployee The first step in creating this polymorphic rowset is to create the HourlyEmployee entity. This entity will hold only those attributes specific to an hourly employee. The attributes that it has in common with other employee entities are defined in the Employee entity. Create the HourlyEmployee entity and extend the Employee entity. In this example the attributes that are specific to an hourly employee are hourlyRate and empType. Add both attributes and set the initial value of empType to H.

Oracle9i JDeveloper: Develop Applications with BC4J 7-19

Creating SalariedEmployee
SalariedEmployee

Create an SalariedEmployee entity commissionPct empType using the Entity Object Wizard. calculatePay() Extend the Employee entity. Include attributes for salary, commissionPct, and empType. Set the default for empType to S.

salary

Copyright Oracle Corporation, 2002. All rights reserved.

Creating SalariedEmployee The second step in creating this polymorphic rowset is to create the SalariedEmployee entity. This entity will hold only those attributes specific to that type of employee. The attributes that it has in common with other employee entities are defined in the Employee entity. Create the SalariedEmployee entity and extend the Employee entity. In this example the attributes that are specific to an salaried employee are salary, commistionPct, and empType. Add both attributes and set the default of empType to S.

Oracle9i JDeveloper: Develop Applications with BC4J 7-20

Adding Custom Methods


Add methods to each entity that override the Employee methods and are specific for each entity. Empoyee
CalculatePay() returns 0 EmployeTypeDescription() returns Unknown

HourlyEmployee
CalculatePay() uses hourlyRate * 40 EmployeeTypeDescription() returns Hourly

SalariedEmployee
CalculatePay() uses salary + commission EmployeeTypeDescription() returns Salaried

Copyright Oracle Corporation, 2002. All rights reserved.

Add Custom Methods Each entity will have methods that are specific to that type of employee. In our example, pay is calculated differently for Hourly and Salaried employees. The pay of hourly employees is calculated as the hourlyRate * 40 hours. The pay for salaried employees is salary + salary * commission percent. Each entity will have a calculatePay() method that returns pay based on its own calculation. Each row in our rowset will use the correct calculatePay() method based on the type of row. If it is an HourlyEmployee the calculatePay() method in that class will be called. Likewise if it is a SalariedEmployee row, the calculatePay() method in that class will be called. You must also decide how to handle an employee who is neither an hourly nor a salaried employee. You must add the custom methods to the Employee entity. They should return values appropriate to an employee who is neither salaried nor hourly. For example, calculatePay may just return 0 and employeeTypeDescription may return Unknown.

Oracle9i JDeveloper: Develop Applications with BC4J 7-21

Create the View Object


Create an EmployeeList view object. Include the subtypes:
HourlyEmployee SalariedEmployee

Copyright Oracle Corporation, 2002. All rights reserved.

Create the View Object The next step is to create a view object that uses the Emp entity and the two subclasses. You first create the view object like any other view object. The only difference is that you include the entity subtypes in the view object. You do that by selecting the Emp entity, then clicking the Subtypes button. The next dialog box will show all the entity objects in your package. Select the two entities that extend the Emp entity.

Oracle9i JDeveloper: Develop Applications with BC4J 7-22

Add Custom Methods to the View Object


Add custom methods to the EmployeeListViewRowImpl.java file
employeeTypeDescription() calculatePay()

Add the methods to the available client row methods in the view object. Add the View object to the application module.
Copyright Oracle Corporation, 2002. All rights reserved.

Add Custom Methods to the View Object Next, edit the EmployeeList view to create the EmployeeListRowImpl.java file if it does not already exist. You will add the two custom methods to EmployeeListRowImpl. The methods call the getEmp() method which returns an Emp entity object. They then call the employeeTypeDescription() or calculatePay() method on the Emp entity object. Because of the polymorphic behavior of the entity, the correct method will be called. public String employeeTypeDescription() { return getEmp().employeeTypeDescription(); } public float calculatePay() { return getEmp().calculatePay(); }

Oracle9i JDeveloper: Develop Applications with BC4J 7-23

Add the Methods to the Views Client Row Methods These methods will be exposed to client applications, that is, they will be the ones called by clients to return the pay and employee type of the employees. Double-click the view object and select the Client Row Methods tab. Add the two methods employeeTypeDescription() and calculatePay() to the Selected list. This makes these methods available to client applications using this view. Add View Object to Application Module The final step is to add the EmployeeListView object to the application module.

Oracle9i JDeveloper: Develop Applications with BC4J 7-24

Create a Test Client


Instantiate the application module. Instantiate the EmployeeList view object. Cast the view object to an EmployeeListRow. Call employeeTypeDescription() and calculatePay().

ViewObject vo = am.findViewObject("EmployeeList"); while (vo.hasNext()) { EmployeeListRow cur = (EmployeeListRow) vo.next(); String EmpType = cur.employeeTypeDescription(); System.out.println("Pay for " + EmpType + " employee " + cur.getAttribute("LastName") + " is " + cur.calculatePay()); }

Copyright Oracle Corporation, 2002. All rights reserved.

Create a Test Client To test the polymorphic behavior of the EmployeeList, you need to create a test client. The client instantiates the EmployeeList view object then steps through the result set calling calculatePay() and employeeTypeDescription() on each row of the result set. The clients output will show the correct employee type and pay for each employee in the result set. It will show that the correct methods were called and that it is transparent to the client and the EmployeeList view object. Note: You have been using the Business Components Tester so far to test your BC4J projects. The Tester is good tool to check business rules and logic that are built in to your entities and view objects. However, it does not provide for code to test specialized methods you may need to add to a project. To test special method calls you must write a test client. A test client is a very simple Java program where you will instantiate an application module and a view object. You can then call methods in the view object. Remember that the entity and view objects are middle-tier objects. The client code you are using to test those objects is client-tier. The full code for the test client is on the following page.
Oracle9i JDeveloper: Develop Applications with BC4J 7-25

Create a Test Client (continued) package mypackage1;

import oracle.jbo.*; import oracle.jbo.domain.Number; import oracle.jbo.client.Configuration; import mypackage1.common.*;

public class TestClient { public TestClient() { }

public static void main(String[] args) { // Fully-qualified name of the application module String _am = "mypackage1.PolyAppModule"; String _cf = "PolyAppModuleLocal";

// Create an instance of the appmodule by name ApplicationModule am = Configuration.createRootApplicationModule (_am,_cf, null);

Oracle9i JDeveloper: Develop Applications with BC4J 7-26

Create a Test Client (continued) // Find the "Managers" view object by name in the app module ViewObject vo = am.findViewObject("EmployeeList"); while (vo.hasNext()) { EmployeeListRow cur = (EmployeeListRow) vo.next();

String EmpType = cur.employeeTypeDescription(); System.out.println("Pay for " + EmpType + " employee " + cur.getAttribute("LastName") + " is " + cur.calculatePay()); } am.getTransaction().commit();

// Disconnect the application module am.getTransaction().disconnect(); }

Oracle9i JDeveloper: Develop Applications with BC4J 7-27

The Results
The test client displays pay based on empType. No casting to HourlyEmployee or SalariedEmployee is required. The correct calculatePay() method is called automatically.
Pay Pay Pay Pay Pay Pay Pay Pay Pay for for for for for for for for for Salaried employee King is 24000.0 Salaried employee Kochhar is 17000.0 Hourly employee De Haan is 1000.0 Salaried employee Hunold is 9000.0 Salaried employee Ernst is 6000.0 Hourly employee Austin is 1140.0 Salaried employee Pataballa is 4800.0 Salaried employee Lorentz is 4200.0 Hourly employee Greenberg is 1000.0

Copyright Oracle Corporation, 2002. All rights reserved.

The Results The output of the test client shows that both salaried and hourly employees are selected in the rowset. It also shows that the correct methods were called depending on the empType of each of the rows.

Oracle9i JDeveloper: Develop Applications with BC4J 7-28

Summary
In this lesson, you should have learned how to: Describe the role of view objects in the business components framework Create view objects Customize view objects using the View Object Wizard Define relationships between view objects Add calculated attributes to view objects Create a polymorphic rowset using entities and a view object

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 7-29

Practice 7-2 Overview


This practice covers the following topics: Adding a calculated attribute to a view object Modifying the source code to recalculate the attribute when the view row changes

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 7-30

Practice 7-2 Start JDeveloper and open the practice07.jws workspace and the Views.jpr project. 1. Add a calculated attribute to the OrderItemsView view object to display the total cost of each line item. To calculate a line items total, multiply the orderItem quantity * the discountUnitPrice. It is also useful to see the inventory items description, so you will also add code to display the item description. a. Add a calculated attribute to the OrderItemsView view object, using the following information: - The name of the attribute is LineTotal. - The attribute displays the total cost of the line item (use the discountUnitPrice). - Use the attribute query expression to calculate the value of LineTotal. b. Edit the OrderItemsView view object and add ProductionInformation.Description to the view objects attribute list. c. Test your changes using the Business Component Browser. 2. Modify OrderItemsView to recalculate LineTotal when the line item changes. In step 1 you added code to calculate the LineTotal when each item is queried from the database. This works fine for initially populating the field. However, when the quantity or discountUnitPrice is changed, the LineTotal must be recalculated. In this step you will add code to calculate LineTotal whenever the getter method is called. You will also add code to recalculate the value whenever other values change on the line item. a. Generate a view row object for LineItem (OrderItemsViewRowImpl.java) if you have not already done so. b. Add the calculation code to the LineTotal getter method. c. Open OrderItemsViewRowImpl.java and add code to the appropriate setter methods that recalculate LineTotal. Note that adding the same code several times is not very good programming practice. Instead, add code to call setLineTotal(null), which will mark the row as dirty and force the framework to perform the recalculation. d. In the View Object Wizard, change the settings for the LineTotal attribute and make this attribute updatable. e. Test your changes using the Business Component Browser. Instructor Note It is a good idea to review the solution for step 2 (in Appendix B) and discuss it with students before they start the practice. The solution forces a recalculation of LineTotal by doing setLineTotal(null), which students may find puzzling. (Note that you can call setLineTotal() with any valid value, null is just the easiest). The way it works is this: The call to setLineTotal(null) sets the view objects cache to a dirty state. The view object knows it must recalculate the value of LineTotal, so it calls getLineTotal() to recalculate the value. Calling getLineTotal() instead of setLineTotal(null) does not force a recalculation of the attribute; it just gets the value from the view objects cache. If students are interested, they could try this and verify that it does not accomplish what is needed.
Oracle9i JDeveloper: Develop Applications with BC4J 7-31

Handling Business Components Transactions

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 45 minutes 60 minutes 105 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Describe the role and functions of an application module Customize the transaction behavior of an application module Describe the locking modes used by business components, and set an applications locking mode Manage application module instances by pooling application modules

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson describes how the business components framework handles database transactions, and explains how you can customize the default behavior. Instructor Note The point to emphasize here is that you do not have to do anything to implement transaction handlingthe Business Components framework does it all for you. This lesson explains how the Business Components framework handles transactions, then talks about how to customize the default behavior.

Oracle9i JDeveloper: Develop Applications with BC4J 8-2

Business Components Transactions


Application modules handle transaction and concurrency support. No coding is required unless you want to customize the default behavior. For nested application modules, the outermost application module provides the transaction context for the others.

Copyright Oracle Corporation, 2002. All rights reserved.

Business Components Transactions The Business Components framework handles all transactions at the application module level. The application module provides a transaction context, with a single database connection. When you commit a change, the commit applies to all view objects in the application module. For nested application modules, the outermost or root application module provides the transaction context for all nested application modules.

Oracle9i JDeveloper: Develop Applications with BC4J 8-3

Application Modules
Represent the data model for clients Track all changes that affect the database Have one connection to the database Provide remotely accessible methods May be deployed to multiple platforms without code changes May contain other application modules

Copyright Oracle Corporation, 2002. All rights reserved.

Application Modules An application module is part of the business logic tier which is accessed by the other tiers. Client applications and the database interact with application modules. The main purposes and functions of an application module are: It represents the data model that clients use and contains business components including instances of view objects and view links. It keeps track of all changes that affect data in the database and manages the transaction context for the top-level module as well as any nested application modules. It provides database connectivity It provides remotely accessible methods which implement the application module behavior. It also holds custom methods that you can write and use for special client processing requirements. It can be deployed to multiple platforms without changes to the code. It can contain other application modules. This ability allows you to design application modules to very specific requirements. For example, one application module may be design for customer information maintenance. Another may be designed for entering and maintaining order information. Both of these modules can be combined into one module that provides both sets of functionality.
Oracle9i JDeveloper: Develop Applications with BC4J 8-4

Application Module Transactions


Transactions manage database interaction. Transactions are treated as an atomic unit. BC4J uses a batch-oriented model to synchronize the cache and database. Changes are buffered in memory. BC4J uses a post operation as part of the commit cycle. Validation occurs when the transaction state changes or just prior to posting.

Copyright Oracle Corporation, 2002. All rights reserved.

Application Module Transactions A transaction is an interface that manages database operations. Business Components for Java application modules provide default transaction and concurrency support. The BC4J framework ensures that each transaction is treated as an atomic unit. That means that all the operations within the transaction must be committed successfully or they will all be rolled back. For example, when a client transfers funds from a checking account to a savings account, three distinct operations occur: decrement the checking account, increment the savings account, and record the transaction. If the transaction were not treated as an atomic transaction, the money could be taken out of the checking account but never deposited into the savings account. Transactions also provide multiuser consistency to a shared store of data. When a client changes data, locks ensure that other clients dont make other changes until the first client is finished. When a transaction is committed or rolled back, the locks are released.

Oracle9i JDeveloper: Develop Applications with BC4J 8-5

Application Module Transactions (continued) The Business Components framework uses a batch-oriented approach to synchronize changes in any cached state with the database state. This approach provides the following benefits: Changes are buffered in an in-memory cache. Changes in the cache are synchronized with the database using a series of database manipulation operations. This series of operations is typically referred to as posting. (In Business Components for Java, posting is performed in the commit cycle, or by specifically calling postChanges() on the Transaction interface.) Validations occur on some combination of each state change that is made and just prior to posting because individual changes may have left the cache in an invalid database state.

Oracle9i JDeveloper: Develop Applications with BC4J 8-6

Accessing a Transaction
Transaction and DBTransaction are interfaces that define database transactions. Use the methods in these interfaces to access an application modules transaction. For example:
ApplicationModuleImpl am; // Commit the transaction am.getTransaction().commit();

Copyright Oracle Corporation, 2002. All rights reserved.

Accessing a Transaction You access an application modules transaction context through the Transaction and DBTransaction interfaces. You can access the methods in these interfaces through the getTransaction() and getDBTransaction() methods in the ApplicationModuleImpl class. Some useful methods of the Transaction interface with regard to application modules are: commit: Commits the transaction; saves all changes to the database. If the database connection is established, the transaction is implicitly started. connect: Attempts to establish a connection to the given database URL. disconnect: Disconnects the server from the database. getLockingMode: Gets the preferred locking mode for this transaction. Currently the locking mode defaults to LOCK_PESSIMISTIC. rollback: Rolls back the transaction; discards all changes. setLockingMode: Sets the preferred locking mode for this transaction. Changing the locking mode affects only subsequent locks that are placed.

Oracle9i JDeveloper: Develop Applications with BC4J 8-7

Accessing a Transaction (continued) The Transaction interface contains a standard set of methods that include commit, set and get LockingMode and so on. The DBTransaction interface extends Transaction. It contains some more specialized methods that deal with entity objects. Some of the methods are findByPrimaryKey(), getSession(), getEnvironment(). For the most part, the Transaction interface provides the methods you will use most often. Instructor Note JDevelopers online help contains the javadoc for the oracle.jbo.Transaction and oracle.jbo.server.DBTransaction. Refer to the javadoc for a complete list of available methods.

Oracle9i JDeveloper: Develop Applications with BC4J 8-8

Committing Transactions

Post phase 1. Validate pending changes. 2. Post updates to the database.

Commit phase. Commit the transaction.

Copyright Oracle Corporation, 2002. All rights reserved.

Committing Transactions The slide describes how the business components framework commits transactions. The commit cycle has two phases: post phase and commit phase. Post Phase First, the framework validates all entity objects that are marked as invalidany new or updated entity object is automatically marked as invalid. This process includes applying all validation rules that you have added in the Entity Object Wizard, as well as executing any custom code that you have added to the entitys validateEntity() method. Because custom validation code itself can change an entity objects data, the validation process is repeated up to ten times, until no entity objects are marked as invalid. Then the updates are posted to the database. Commit Phase The transaction is committed, and the updated data is available to other application modules.

Oracle9i JDeveloper: Develop Applications with BC4J 8-9

Compositions and the Commit Cycle


For entities not related by a composition, the order in which changes are validated and posted is not guaranteed. For entities related by a composition, the order of validation and posting is guaranteed.
Source entity Composition Destination entity

Validates first Posts changes first

Validates second Posts changes second

Copyright Oracle Corporation, 2002. All rights reserved.

Compositions and the Commit Cycle When two entities are not related by a composition, there is no guarantee of the order in which changes are validated, or of the order in which changes are posted to the database. If, on the other hand, two entities are related by a composition, then the order of events is guaranteed: If the destination entity is changed, both the destination entity and the source entity are marked as invalid. During the commit cycle, the source entity is validated before the destination entity. Changes to the source entity are posted to the database before changes to the destination entity. This guarantees that foreign key constraint errors will not occur. Entities that are related through a composition are strongly related. That means that the destination (detail) entity cannot exist without the source (master). In a relation sense, most entities that are related by a primary key and foreign key are considered to be a composition association. The default for creating a new association is not a composition.

Oracle9i JDeveloper: Develop Applications with BC4J 8-10

Customizing the Post Phase


Override the entity objects postChanges() method. Example: For a deleted entity, mark the database row instead of deleting the data.

public void postChanges(TransactionEvent e) { if (getPostState() == Entity.STATUS_DELETED) { // Custom code to mark database rows } else { super.postChanges(e); } }

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing the Post Phase You can customize the behavior of the post operation by overriding EntityImpl.postChanges(). The slide shows an example of this. The code in the example calls getPostState() to determine the entitys post state. The post state is the state of the entity object's data relative to the transaction's corresponding database data. The Entity interface contains a number of constants that define the possible values for an entitys post state. The post state is set to STATUS_UNMODIFIED when the data is posted to the database. Instructor Note An example of using this technique is to intercept a delete action and to mark only the deleted rows as deleted, without actually removing them from the table. You would use this technique if you wanted to preserve history of deleted rows.

Oracle9i JDeveloper: Develop Applications with BC4J 8-11

Customizing the Commit Phase


Implement a TransactionListener. Implement beforeCommit() and afterCommit(). Add your listener to the transactions list of event subscribers. Alternatively, override the entity objects beforeCommit() or afterCommit() methods.

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing the Commit Phase The TransactionListener interface defines beforeCommit() and afterCommit() methods. You can implement a transaction listener and add it to the transactions list of event listeners by calling the transactions addTransactionListener() method. For example, in an entity objects code, call: getTransaction().addTransactionListener(myTransListener); Your entity objects are also transaction listeners, and are already on your transactions list of event listeners. Because of this you can also override an entity objects beforeCommit() and afterCommit() methods. Customizing Rollback The procedure for customizing rollback behavior is similar to the procedure for customizing commit behavior. The TransactionListener interface also defines beforeRollback() and afterRollback() methods that are called before and after a rollback operation.

Oracle9i JDeveloper: Develop Applications with BC4J 8-12

Locking Modes Supported by Business Components


Pessimistic locking: Locks are automatically placed on the underlying row the first time that an attribute is modified. Optimistic locking: Locks are automatically placed on the underlying row when the data is committed. No locking: Locks must be placed by explicit calls from the client. If no lock calls occur, then only the database locks, which are obtained when the rows are flushed to the server, are obtained. By default, all entities use pessimistic locking.

Copyright Oracle Corporation, 2002. All rights reserved.

Locking Modes Supported by Business Components The slide describes the three locking modes supported by the Business Components framework. With pessimistic locking, a lock is placed on the underlying database row as soon as an attribute changes in the entity objects data cache. With optimistic locking, a lock is placed on the database row only when the change is committed to the database. Instructor Note You can designate a database column to be used as a change indicator for optimistic locking. You do this by selecting Change Indicator in the Attribute Settings tab of the Entity Object Wizard.

Oracle9i JDeveloper: Develop Applications with BC4J 8-13

Getting and Setting the Locking Mode


To get the locking mode:

int lockmode = am.getTransaction().getLockingMode(); if (lockmode == Transaction.LOCK_PESSIMISTIC){} else if (lockmode == Transaction.LOCK_OPTIMISTIC){}

To set the locking mode:

am.getTransaction().setLockingMode( Transaction.LOCK_NONE);

Copyright Oracle Corporation, 2002. All rights reserved.

Getting and Setting the Locking Mode If you do not want to use pessimistic locking mode (the default), you can change the locking mode at run time. The example on the slide shows how to do this, by calling Transaction.setLockingMode().

Oracle9i JDeveloper: Develop Applications with BC4J 8-14

Application Module Pooling


The Business Components framework does its pooling at the application module level. There is a pool of instances for each application module. Each instance has its own database connection.
OrderModule pool PaymentModule pool

Copyright Oracle Corporation, 2002. All rights reserved.

Application Module Pooling Application pooling is a technique where multiple instances of an application module are created before a client asks for one. When a client needs one, it gets one from the pool without the overhead of the creation step. When the transaction is either committed , rolled back, or the session terminates, the application module instance is returned to the pool to wait for the next request. This pooling technique applies to applications deployed in a two-tier model. When an application is deployed in a three-tier mode, the EJB container manages its own pool. For example your two-tier application may have 1000 users, but you know that only 100 or so will be using the application at any given time. In this case, you would want the pool to precreate 100 application modules and share them among users as needed. The application module pools are managed by the pool manager; there is only one pool manager per JVM instance. The purpose of application module pooling is to minimize the cost of server-side resources for the client.

Oracle9i JDeveloper: Develop Applications with BC4J 8-15

Application Module Pooling (continued) Application Modules and Database Connections Each application module instance has one database connection and keeps the same connection throughout its lifetime. Clients connect to application modules; in this way each client has its own middle-tier connection. Instructor Note Application module pooling is not useful for three-tier applications, because the pool is managed by the Java client. This means that it is only appropriate for JSP and servlet clients.

Oracle9i JDeveloper: Develop Applications with BC4J 8-16

Application Module Pooling: Default Behavior


1. The client requests an application module instance. 2a. The pool manager checks out an instance.

2b. If there are no free instances, the pool creates a new one.

3. The client releases the instance which is checked in to the pool.

Copyright Oracle Corporation, 2002. All rights reserved.

Application Module Pooling: Default Behavior The slide shows how application module instances are used. When the client requests an application module, an application module instance is checked out of the pool. When it is released, it is checked in to the pool, keeping its database connection. If there are no idle instances when a request arrives, the individual pool creates a new instance.

Oracle9i JDeveloper: Develop Applications with BC4J 8-17

Application Module Pool Parameters


You control the pool with the parameters: initpoolsize: The initial number of instances Poolmaxavailablesize: Maximum inactive instances Poolminavailablesize: Minimum inactive instances Poolmaxinactiveage: Maximum time an instance can be inactive before being flagged for removal poolmonitorsleepinterval: Amount of time between high water triggers

Copyright Oracle Corporation, 2002. All rights reserved.

Application Module Parameters The application module pool manager is controlled by parameters that you set in the application module configuration. You find the parameters by editing the application module configuration. To edit the configuration, right-click the application module and select Configurations. Next click the Edit button. This opens the Business Component Configuration Wizard. Select the Properties tab to see and edit the configuration properties. The parameters are listed in alphabetical order by default. The properties that control the application module pool manager begin with jbo.ampool. Removing Instances Application module instances are removed from the pool as follows: The pool manager compares the number of inactive, available instances in the pool against the minimum available instance size. If the number of inactive, available instances is greater than the minimum available instance size, then the pool will attempt to remove any inactive, available instances. An inactive instance is defined as an instance that has been unused for a period longer than the pools maximum inactive age. The pool will continue to remove inactive, available application module instances until the minimum available instance size has been reached or there are no more inactive, available instances.

Oracle9i JDeveloper: Develop Applications with BC4J 8-18

Application Module Parameters (continued) Removing Instances (continued) The pool manager compares the number of available instances in the pool against the maximum available instance size. If the number of available instances is greater that the maximum available instance size, the pool attempts to remove any available instances. The pool will continue to remove available instances until the maximum available instance size has been reached or there are no more available instances.

Oracle9i JDeveloper: Develop Applications with BC4J 8-19

Managing Transaction State


You can release transactions back to the pool in one of three (3) states: Stateful: The state of the transaction is saved. Stateless: The state of the transaction is not saved. Reserved: The application module instance is reserved for a single HTTP session and will not be recycled.

Copyright Oracle Corporation, 2002. All rights reserved.

Managing Transaction State Application module pooling is used to improve performance of Web-based applications, either JSPs or Servlets. Because an HTTP session is inherently stateless, BC4J manages the state using the application module pool. When you write a JSP application, you must check out an application module, process the data and then release the application module back to the pool. The way in which you release the application module is critical to the performance of your application. There are three (3) release modes. Release Modes Stateful: In a Stateful JSP application, the data tags or data Web beans of a JSP application do not necessarily access the same application module instance each time they are invoked. However, Business Components for Java saves the application module state to the database, file, or memory when the application module is released, and allows a view objects rowset to remain the same from one invocation to the next. Stateful mode provides failover support from the database and still allows application modules to be recycled. However, you may need to use the stateless mode when you expect many users to access your JSP application simultaneously. The stateless option may allow more users to access a JSP application simultaneously. The downside is that the action of saving the state of the module instance state and resetting the instance for reuse (called passivation) is an expensive process.
Oracle9i JDeveloper: Develop Applications with BC4J 8-20

Managing Transaction State (continued) Stateless: When you select the stateless option for individual JSP pages or the entire JSP application, the data tags or data Web beans do not necessarily access the same application module instance each time a new page is invoked during a specific HTTP session and, therefore, cannot depend on a view objects rowset remaining the same from one invocation to the next. Each HTTP session does not get its own instance for each application module; instead, all HTTP sessions share a limited pool of instances of each application module. This option saves processing in that it does not passivate the application module instance. Reserved: When you select reserved mode for individual JSP pages or the entire JSP application, after a data tag or data Web bean has connected to an application module, all subsequent connections to that application module from any data tag or data Web bean during the same HTTP session involve the same instance of the application module. This holds true whether a subsequent connection is from another JSP page or from a new invocation of the same JSP page. This mode is similar to the stateful application, but it does not provide failover support nor does it permit application modules to be recycled. Reserved mode is provided primarily for compatibility with application modules that use nonstandard JDBC connections. You can use reserved mode to hold pessimistic locks between HTTP requests.

Oracle9i JDeveloper: Develop Applications with BC4J 8-21

Summary
In this lesson, you should have learned how to: Customize the Post phase of a transaction Customize the Commit phase of a transaction Access and modify the locking mode of a transaction Describe application module pooling Describe the three (3) release modes used by the application module pool manager

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 8-22

Practice 8-1 Overview


This practice covers the following topics: Testing pessimistic locking using the Business Components Browser Testing optimistic locking using the Business Components Browser Setting the locking mode for a transaction in a batch client

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 8-23

Practice 8-1 Start JDeveloper, and open the practice08.jws workspace. Simulate two users using two separate instances of your application module trying to update the same record. In the first part, you will use pessimistic locking mode, which is the default behavior. In this practice, you will use the Business Components Browser to show how different locking modes affect multiple users. In a later practice, you will add code to a client application to manipulate the locking mode. 1. Simulate multiple-user updates using pessimistic locking. a. Open and rebuild the Locking project. b. Run the Business Components Browser on the application module, and designate this instance as User1. c. Run the Business Components Browser on the application module again, and designate this instance as User2. You should now have two separate instances of the browser. d. In the browser that you designated as User1, check the value of Transaction.LockMode by right-clicking the application module name and selecting Properties. The value should be 1, which indicates pessimistic locking. Remember pessimistic locking is the default. e. Open an instance of OrdersView in both browsers (User1 and User2). f. Both browsers should display the same row of data. If they do not show the same record, scroll through the result set until they display the same row. g. In User1, enter a value in Promotion Id, and then tab out of the field to write the change to the entity objects cache (do not save the change). h. In User2, enter a different value in Promotion Id and then click the green arrow (Commit button). i. Notice the error JBO-26030: Failed to lock the record; another user holds the lock. j. Dismiss the error message, and then click the red arrow (rollback) in User1. You can now save the change to User2. k. Close both tester windows. 2. Simulate multiple-user updates using optimistic locking. a. As in step 1 of this exercise, run the Business Components Browser on the application module twice and designate one instance as User1 and the other as User2. b. Change the value of Transaction.LockMode to optimistic in both instances of the application model. Click another property to make the change stick, and then click Close. c. Double-click OrdersView in User1 and in User2. Make sure both users are displaying the same row of data. d. In User1, enter a value in Promotion Id, and then tab out of the field to write the change to the entity objects cache (do not save the change). e. In User2, enter a value in Promotion Id, and then click the green arrow (Commit button). Notice that there is no error. f. Click the Commit button in User1. Notice the error that another user has changed the same row. g. Dismiss the error message and close both tester windows.

Oracle9i JDeveloper: Develop Applications with BC4J 8-24

Packaging Business Services and Data Models

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 45 minutes 30 minutes 90 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Create an application module Define an application modules data model Add service methods to an application module

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson covers application modules in more detail, including how to design an application module and how to define an application modules data model.

Oracle9i JDeveloper: Develop Applications with BC4J 9-2

Overview
OrderManagementApp Application tasks Transaction handling

PriorityOrder

ItemList

Customers

Orders OrderItems

Copyright Oracle Corporation, 2002. All rights reserved.

Overview The slide shows an example of an application module. The application module acts as a wrapper for the views and entities in your business model. It also handles all database transactions and can perform tasks that are specific to the application.

Oracle9i JDeveloper: Develop Applications with BC4J 9-3

Application Module
An application module:
Defines the data model and business services for a task in your application Contains views and view links Can contain other application modules Can contain service methods

Clients interact with application modules

Copyright Oracle Corporation, 2002. All rights reserved.

Application Module An application module performs a specific application taskfor example, handling online orders or processing customer information. An application module has these main characteristics: It represents the data model that your client uses. It lets you gather data tailored to a client interface (such as a form), so that data can be retrieved in one network round-trip instead of multiple trips. It can contain other application modules, called nested application modules. It keeps track of all changes that affect data in the database. It provides remotely accessible methods, which implement the application module behavior. A top-level application module has one connection to the database. You can deploy the same application module in multiple configurations such as CORBA, EJB, or locally, without changing its code. As discrete units, application modules are easily reused in the business logic tiers of other applications.

Oracle9i JDeveloper: Develop Applications with BC4J 9-4

Designing Your Application Modules


One application module per functional unit:
Panel displaying related data Application that performs a particular function

Design application modules for reuse in different contexts. Application modules should not contain details of the deployment method.

Copyright Oracle Corporation, 2002. All rights reserved.

Designing an Application Module You should design an application module to handle a particular task in your application. There are no fixed rules for determining what constitutes a task; you have to determine what works best for your application. One possibility is to create an application module corresponding to each panel in your client applications user interface. You can add metadata to your application that the client uses to determine how to render each panel and how the different view object instances interact with each other. The top-level application module provides a transaction context for the view object instances that it contains, including those in all nested application modules. Thus, the user can make changes to any of the view objects within this transaction context and save all the changes at once. However, a single transaction (save) cannot span multiple top-level modules. This is also an important consideration when deciding what application modules your application needs. Creating an Application Module To create an application module, right-click the package icon in the navigator, and select Create Application Module from the context menu.
Oracle9i JDeveloper: Develop Applications with BC4J 9-5

Files Generated for the OrdModule Application Module


OrdModuleImpl.java: The application module class
Generation is optional Controls the application modules behavior

OrdModule.xml: Metadata
Always generated The Application Module Wizard gets all its information from this file

Copyright Oracle Corporation, 2002. All rights reserved.

Files Generated When you create a business components application using the Business Component Project Wizard, JDeveloper generates two files for each application module: AppModule.xml (for example, OrdModule.xml). This file contains metadata for your application module. AppModuleImpl.java (for example, OrdModuleImpl.java). This is the application module class; it is a subclass of oracle.jbo.server.ApplicationModuleImpl. This file is generated by default, but you can remove the class from the Application Module Wizard.

Oracle9i JDeveloper: Develop Applications with BC4J 9-6

About the Data Model


Consists of the set of views and view links in the application Contains unrestricted (master) views and restricted (detail) views
AppModule1 CustomersView OrdersView via OrderPlacedByLink Unrestricted view Restricted view

Copyright Oracle Corporation, 2002. All rights reserved.

About the Data Model Each application module has a data model. Although conceptually an application module is a wrapper for the entities, views, associations, and view links in an application task, its data model contains only views and view links. The underlying entities and associations are included by implication. Restricted and Unrestricted Views In the application module shown on the slide, CustomersView is an unrestricted view and OrdersView is a restricted view. When you run the application module, CustomersView can display all rows of customer data, but OrdersView can display only the order data associated with the current customer. When you add a view to your application modules data model, you need to decide whether you want to add it as an unrestricted view or as a restricted view.

Oracle9i JDeveloper: Develop Applications with BC4J 9-7

Defining the Data Model


Use the Data Model tab of the Application Module Wizard.

Select an insertion point.

Select a view.

Add the view to the data model.

Copyright Oracle Corporation, 2002. All rights reserved.

Defining the Data Model Define the data model in the Data Model tab of the Application Module Wizard. The Available Views Pane This pane contains the list of views in the package containing the application module. The way in which each view is shown depends on the view links to which it belongs. For example, in the available views pane on the slide: CustomersView is shown once, as the source view in OrdersCustomerIdFkLink. It can be added to the data model only as an unrestricted view. OrdersView is shown twice, as the destination view in OrdersCustomerIdFkLink and as the source view in OrderItemsOrderIdFkLink. You can add OrdersView to your data model as a restricted view, by clicking the first OrdersView node, or as an unrestricted view, by clicking the second OrdersView node. OrderItemsView is also shown twice. You can add OrderItemsView to your data model as a restricted view, by clicking the first OrderItemsView node, or as an unrestricted view, by clicking the second OrderItemsView node. OrderItemsView is not a source view in any link. The Data Model Pane The Data Model pane shows the application modules data model. In the example shown on the slide, OrderItemsView is about to be added as an unrestricted view, because it is being inserted under the top level of the data model tree.
Oracle9i JDeveloper: Develop Applications with BC4J 9-8

The Wizard Ensures a Valid Data Model


The Add button is disabled for invalid selections.

The Add button is disabled because you cannot add OrderItemsView as a child of CustomersView.
Copyright Oracle Corporation, 2002. All rights reserved.

The Wizard Ensures a Valid Data Model In the example on the slide, the right arrow (add) button is disabled, because you cannot add OrderItemsView as a restricted view with CustomersView as its parent. Instructor Note You can ask students some questions here: 1. What could you select in the Available Views pane that would enable the add button? Answer: The first listing of OrdView. That is the only view that can be added to the data model as a restricted view with CustomersView as its parent. Selecting the second listing of OrdView would not enable the add button. 2. What could you select in the Data Model pane that would enable the add button? Answer: The top-level node (Package11Module.) Then you could add LineItemView to the data model as an unrestricted view.

Oracle9i JDeveloper: Develop Applications with BC4J 9-9

Nesting Application Modules


Application modules can be made up of other application modules.
Q1 Sales
Top Suppliers Top Suppliers

TopSupplierModule SalesModule TopSupplierModule


Copyright Oracle Corporation, 2002. All rights reserved.

Nesting Application Modules Application modules can be nested. In the example on the slide, TopSupplierModule is used in two contexts: nested in SalesModule, and on its own as a top-level module. By adding custom code or custom properties to TopSupplierModule, you can change the way it is displayed in different contexts. For example, you might want it to display a more restricted data set when it is used as a nested module. You can do this by adding custom code to your application module to restrict TopSupplierModules SQL query. Instructor Note Custom properties are covered later in the lesson. In practice, more than one level of application module nesting is unusual.

Oracle9i JDeveloper: Develop Applications with BC4J 9-10

Nesting Application Modules


Use the Application Modules tab of the Application Module Wizard. An application module cannot be nested inside itself.

Copyright Oracle Corporation, 2002. All rights reserved.

How to Nest Application Modules 1. In the Application Module Wizard, select the Application Modules tab. 2. Select an application module in the available list, and use the right arrow button to move it to the select list. 3. Click Apply or Finish.

Oracle9i JDeveloper: Develop Applications with BC4J 9-11

Adding Service Methods to an Application Module


Useful for methods that are not used by all instances of an application Useful for code that is not dependent on a specific view More efficient than executing the method on the client More efficient than adding the method to the view object; the method is available only to those applications that need it Add application-specific code to AppModuleImpl.java

Copyright Oracle Corporation, 2002. All rights reserved.

Adding Service Methods to an Application Module Service methods are methods that are specific to an application module. These methods may be independent of any view in the application. For example, you may need a method that determines the number of current orders for a specific item in inventory. That method can be used from any client without needing to instantiate an inventory or order view. You can also add code that affects the behavior of a particular view object in the application module; for example, you can change the WHERE or ORDER BY clause of a view object. You would do this if you were reusing a view object in multiple application modules and wanted the view object to behave differently in different application modules. Because you can use a view object in multiple applications, a view object may contain custom code that is used by only one application module. In this case, you should move the custom code to the application module that uses it so that it is available only to those applications that need it. Example: Deciding When to Add Custom Code to an Application Module Two application modules, OrderManagementApp and CustomersApp, both have CustomersView in their data model. CustomersApp requires custom code to perform analysis of customers purchasing history; OrderManagementApp does not need this information. Adding this code to CustomersView would add size and complexity to the view object for the sake of functionality that will never be used by OrderManagementApp. Therefore, you should add your custom code to the CustomersApp application module.
Oracle9i JDeveloper: Develop Applications with BC4J 9-12

Adding Custom Properties to an Application Module


Specify your own name-value pairs of metadata. Add properties in the Application Module Wizard.

To get a propertys value in your application module code:


String displayType = (String)getProperty("displayType");
Copyright Oracle Corporation, 2002. All rights reserved.

Adding Custom Properties to an Application Module Custom properties allow you to specify your own metadata that the Business Components framework can access at run time. In the example on the slide, two custom properties have been added to an application module. A client could access these properties to determine how to display the data in this application module and who can access this application module. How to Add a Custom Property to an Application Module 1. In the Application Module Wizard, select the Properties tab. 2. Enter the name and value of your property, and then click Add. 3. Click Apply or Finish. How to Access Property Values at Run Time The jbo.server.ApplicationModuleImpl contains the methods getProperty() and setProperty() to get and set the values of a custom property. JDevelopers online help contains the javadoc for these methods. Adding Custom Properties to Other Component Types You can also add custom properties to entity objects, view objects, entity object attributes, view object attributes, and domains.
Oracle9i JDeveloper: Develop Applications with BC4J 9-13

Summary
In this lesson, you should have learned how to: Explain how an application module handles a particular task in your application Describe a data model that contains restricted and unrestricted views and view links Nest application modules Add your own custom properties to an application module

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 9-14

Practice 9-1 Overview


This practice covers the following topics: Modifying an application modules data model Creating nested application modules Adding service methods to an application module

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 9-15

Practice 9-1 Start JDeveloper, and open the practice9.jws workspace and the AppModule.jpr project. 1. Remove views from the application modules data model. a. Right-click the application module and select Edit Practice10Module from the shortcut menu. b. Remove views from your application module until it looks like the following screenshot. Notice how the left-arrow button (<) is enabled and disabled as you click through the views in the data model.

c. Click Finish to save your changes. 2. Add views to the application modules data model. Add views to your application module so that it looks like the data model in the following screenshot. OrderItemsView appears three times in this data model: - As a restricted view, meaning that the data in this view depends on the value selected in the source view (in this case, ProductInformationView and OrdersView) - As an unrestricted view, meaning that all rows of data are available a. In the list of available views, select one of the occurrences of OrderItemsView . In the data model, select the point where you want to insert this view. Notice that the right-arrow button (>) is enabled only when you have selected a valid insertion point for your view and that there is only one valid insertion point for the view that you have selected. b. Click the right-arrow button (>) to add the view to the data model. c. In the list of available views, select another occurrence of OrderItemsView . In the data model, select the valid insertion point for your view. d. Click the right-arrow button (>) to add the view to the data model. The model should look like the model below.

Oracle9i JDeveloper: Develop Applications with BC4J 9-16

Practice 9-1 (continued) 2. Add views to the application modules data model. (continued) e. Select Finish to save your changes. f. Test your new data model in the Business Component Browser. Open an instance of each of the OrderItemsView views. Undock each of the views and navigate through some rows of each view. Notice the difference in the data that is available to you from the two different occurrences of OrderItemsView. 3. Create nested application modules. Create a root application module containing two other application modules. a. Create a new application module in the same package. In the Application Module Wizard, choose a name for your new application module, and then add whatever views you want to its data model. This screenshot shows one possible data module for your application module.

b. Still in the same package, create another application module. Call your new module RootModule and do not add any views to its data model. Instead, add two application modules: the one you created in step 3a and the one you created in step 2. c. Save your changes, and test RootModule using the Business Component Browser.

Oracle9i JDeveloper: Develop Applications with BC4J 9-17

Extending and Substituting Business Components

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 45 minutes 45 minutes 90 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Extend the metadata of an application Extend the Java classes of an application Replace all occurrences of an object throughout an application

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson shows you the features available in JDeveloper9i that you can use to customize your business components. As you have seen, JDeveloper9i uses XML to store information about your business components. Because this metadata is stored as XML, it can be easily modified to customize the data model and default behavior.

Oracle9i JDeveloper: Develop Applications with BC4J 10-2

Overview
There are two customization models:
Use existing objects with your own objects Enhance existing objects to meet your needs

JDeveloper9i easily supports both models Examples of customization:


Build a custom application around existing components Enhance an existing application without modifying source code

Copyright Oracle Corporation, 2002. All rights reserved.

Overview Using JDeveloper, you can easily extend and enhance BC4J applications, even if you don't have the source code. Consider the following two scenarios: Scenario One: Using existing components in a custom application There are several development efforts in progress at your company. One team has developed a complete set of objects to manage employee information. Your team is working on a financial project that needs an employee object. You could develop your own employee object but you don't know all of the business rules associated with an employee. Using JDeveloper, you can import the employee object into your project and build it into your application. You don't need the source code, so the employee information team maintains control of the business rules for the employee. Scenario Two: Enhancing an existing application without source code Your company has just purchased a software package to manage online ordering. The package meets most of your needs, but it needs to have a few attributes and business rules added to the Customers object. Using JDeveloper, you can import the package and extend the Customers object to include the new rules. You then build an application that combines the original application with your enhancements. You can accommodate either of the scenarios using the extend and substitute capabilities of JDeveloper.
Oracle9i JDeveloper: Develop Applications with BC4J 10-3

Using Existing Objects with your Objects


To use objects from an existing Business Components project in your new project: Add the original .jar file to the new project. Import the original application into the project. Use View Objects from the original application in your application modules.

Copyright Oracle Corporation, 2002. All rights reserved.

Using Existing Objects with Your Objects To use existing objects with your objects, you simply load the original application into your new project. This makes the objects from the existing application available to your new application. Add the original .jar file to the projects libraries. Import the original application into the new project. Now that your new project has access to the original application, you can add View Objects from the existing application to the Application Modules of your new application. You can also use this same technique to break large projects into multiple smaller projects. For example, you might create a separate project for each major functional area of your new application, importing as needed. The next slides discuss what to do if you need to extend or customize the existing object before using it.

Oracle9i JDeveloper: Develop Applications with BC4J 10-4

About Customization
Customization is efficient because of the business components framework:
Metadata is cleanly separated from Java implementation. An application can be customized even without access to source code.

Customizations are layered on top of existing code. Customized components can reside in any package.

Copyright Oracle Corporation, 2002. All rights reserved.

Customization and JDeveloper Customization is inevitable because no component vendor can provide all the features that you need in just the way that you want. Because JDeveloper9i adopts the XML model, the process of customization is easy. Specifically: Metadata is cleanly separated from program code (in this case, Java). Using JDeveloper9i and BC4J, you can customize your application without access to source code. This typically involves obtaining the generic business components from a third-party vendor (in the form of class files and XML files, all in one .jar file) and then adding XML text and Java code on top of these classes. As in other Java-based software, your customized code and XML text can be in any package.

Oracle9i JDeveloper: Develop Applications with BC4J 10-5

Customization Concepts
You can update relevant XML files from within JDeveloper. You can update relevant Java implementation files. At run time, any request for the new component returns an implementation that includes all of the new features.

Copyright Oracle Corporation, 2002. All rights reserved.

Customization Concepts There are two stages in the customization process: First, update relevant XML files. You do this in a systematic fashion within JDeveloper9i instead of using an editor such as vi and notepad. This way, you get the benefits of using the JDeveloper9i wizards in your customized code also. Second, your new customization will in all likelihood require additional Java code. You need to create new methods or update existing methods.

Oracle9i JDeveloper: Develop Applications with BC4J 10-6

Customizing an Application
To enhance an existing application to include specific business rules and new data elements: Add the original .jar file to the new project. Import the original application into the project. Create a new entity that extends the original entity. Modify the new entity to reflect your new attributes and business rules. Create a view based on the extending entity. Add a substitution entry to the project.

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing an Application There are a few steps required to begin the customization process. The first steps simply load the original application into your new project. This makes the application available to JDeveloper9i so that you can enhance existing components. These steps are: Add the original .jar file to the projects libraries. Import the original application into the new project. Now that your new project has access to the original application, you need to create a new component that extends the original component. You then modify it to reflect the new business rules and data model. After you have completed the modifications, use the Business Components Project Wizard to add a substitution clause to the project. The application now dynamically substitutes the new component for each occurrence of the old component. Note: The following slides explain these steps in detail.

Oracle9i JDeveloper: Develop Applications with BC4J 10-7

Example of Customization
Can you reuse the existing Customers entity object when a new attribute is added?
Entity object Attributes Customers
ID Name Status Email Credit Limit

Database table

ID 201 202

Name Steve Mike

Credit Limit 1,000 5,000

Email Steve@myComp... Mike@theOther...

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing an Application (continued) As an example, consider that you have obtained a generic business component that performs a certain functionality. Unfortunately, the database table that it models does not have exactly the same columns as the one you have. In particular, you have a new column, credit_limit, designed to keep track of the current limit on the credit of a customer. Can you reuse the existing business component and the application, but have it model your table? The answer, as you will see, is yes.

Oracle9i JDeveloper: Develop Applications with BC4J 10-8

Example of Customization

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing an Application: Example The first step in adding enhancements to an existing application is to make the application available to JDeveloper. This is a two-step process. Add the .jar file that contains the application to the project libraries. This allows JDeveloper9i to include the .jar file in the execution classpath. Import the business components into your project. This makes the classes available to your BC4J project, and you can use them as the base for your new enhanced application. You import Business Components using the shortcut menu on the Project node. Select Import Business Components. This invokes the Import Business Components Wizard. In the wizard, select the .jar file you want to import. Drill down into the .jar file to find the Application Module .xml file. Select this file to import all of the Business Components into your project. The original application is now available in read-only mode. You have access to the application module so that you can run the Business Components Browser, but you cannot modify the application in any way. Next, create components that extend the original components and apply the enhancements.

Oracle9i JDeveloper: Develop Applications with BC4J 10-9

Example of Customization

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing an Application: Example (continued) Creating the Component Now that the project has access to the original application, you can begin enhancing the components. You must first create a new component based on the original. In the example, create a new Customers entity based on the original Customers entity in the OrderEntry package. To create a new entity object that is based on the original, select Create Entity Object from the shortcut menu. Click the Browse button to the right of the Extends Entity field in the wizard. Click the entity that you want to extend.

Oracle9i JDeveloper: Develop Applications with BC4J 10-10

Example of Customization

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing an Application: Example (continued) In the next step of the wizard you can add new attributes. As with any entity, they can be based on a table or be transient. After you select or create the attributes, you can complete detailed information about the attribute. Because you are creating a new entity, you also have the opportunity to generate Entity Definition and Entity Object classes. You can also generate a default view object.

Oracle9i JDeveloper: Develop Applications with BC4J 10-11

Example of Customization

Copyright Oracle Corporation, 2002. All rights reserved.

Customizing an Application: Example (continued) After you have created the new view, you need to add it to the application data model. Remember that you are extending an existing application, so your changes can only go into the new application. After you have added the view to the data model, you can test your view using the Business Components Browser. You should be able to see the original view and your new view at the same time. Notice the new view has the creditlimit attribute.

Oracle9i JDeveloper: Develop Applications with BC4J 10-12

Looking at the XML


Maintains the reference to the original definition Contains definitions for only the differences from the original
<?xml version="1.0" encoding='WINDOWS-1252'?> <!DOCTYPE Entity SYSTEM "jbo_03_01.dtd"> <Entity Name="CustomersEx" Extends="OnlineOrders.Customers" DBObjectType="table" DBObjectName="CUSTOMERS"

Copyright Oracle Corporation, 2002. All rights reserved.

Looking at the XML When you extend an existing object, JDeveloper9i modifies the .xml files it uses to keep track of object properties. In this example, the Customers.xml file contains and extends property with a value that references the original Customers entity. You do not need to modify any of the .xml files manually.

Oracle9i JDeveloper: Develop Applications with BC4J 10-13

Factory Substitution
Assume that you have been provided a business component application by a third party. Sometimes you may want to:
Keep some entities as they are Use a completely different model for other entities

Example: Use a customized version of the Customers entity based on your tables. Factory substitution is useful in such cases.

Copyright Oracle Corporation, 2002. All rights reserved.

Factory Substitution Factory substitution is similar and even related to extending an object. With an extension, you can use the original version of an entity, and expand or customize it for your specific requirements. Then, you build a set of related components to leverage the business rules in the original object. With substitution however, you completely replace the definition of one object with another. Note that the object you are substituting can either be completely new or an extension of an existing object. In the example, take the Customers object that was extended by adding credit limit and substitute it for the original Customers. The new application looks and behaves like the original, except that it has one new attribute.

Oracle9i JDeveloper: Develop Applications with BC4J 10-14

Example Using Factory Substitution


Can you change the existing Customers entity object completely, even while keeping other objects in the application?
Entity object Attributes Customers
ID Name Status Email Credit Limit

Database table

ID 201 202

Name Steve Mike

Credit Limit 1,000 5,000

Email Steve@myComp... Mike@theOther...

Copyright Oracle Corporation, 2002. All rights reserved.

Example Using Factory Substitution The slide shows an example of a situation that you might encounter. The answer to the question posed in the slide is Yes, of course. Our example is rather simple but it could be a complete, even radical, replacement of the Customers entity. The new entity can even have a completely different name, for example, Patron.

Oracle9i JDeveloper: Develop Applications with BC4J 10-15

Performing Factory Substitution

Copyright Oracle Corporation, 2002. All rights reserved.

Performing Factory Substitution To direct JDeveloper9i to use one entity in place of another, select Edit Business Components Project from the Projects context . In the project settings dialog box, select the Substitution tab. The Substitution tab shows all of the objects available in the application. Select the object in the left-hand pane that you want to override. Then select the object in the right-hand pane that you want to use in its place. Click the Add button to add the substitution to the project. Repeat these steps until you have specified all of the substitutions for the project. When you click Finish, JDeveloper9i modifies the .xml files to use the new objects whenever the original objects are referenced.

Oracle9i JDeveloper: Develop Applications with BC4J 10-16

The Finished Substitution

Copyright Oracle Corporation, 2002. All rights reserved.

The Finished Substitution In this sample substitution, you: Imported the Customers Entity object from an existing Business Components application Extended the Customers entity object to include a new attribute from the Customers table Created a new CustomersView to the application model Tested the application to see that there are two different views, the original view without Creditlimit, and the new view with Creditlimit Added a substitution to the project that substitutes the new Customers entity and view for the originals, whenever they are referenced In the preceding slide, note that after the substitution, the CustomersView now includes Creditlimit. It also shows that the OrdersPlacedBy view includes Creditlimit because it references Customers.

Oracle9i JDeveloper: Develop Applications with BC4J 10-17

Looking at the XML

<?xml version="1.0" encoding='WINDOWS-1252'?> <!DOCTYPE JboProject SYSTEM "jbo_03_01.dtd"> <JboProject Name="Extend" SeparateXMLFiles="true" PackageName="" > <Substitutes> <Substitute OldName "OnlineOrders.CustomersView" NewName ="extend.CustomersView" /> <Substitute OldName ="OnlineOrders.Customers" NewName ="extend.Customers" /> </Substitutes> </JboProject>

Copyright Oracle Corporation, 2002. All rights reserved.

Looking at the XML JDeveloper9i modified the project .xml file to include the substitution information. The Business Components framework reads this file at run time and makes the global substitution.

Oracle9i JDeveloper: Develop Applications with BC4J 10-18

Summary
In this lesson, you should have learned how to: Make use of and extend business components provided to you Change the model of one or more entities provided to you in your business component application module, even while keeping other entities the same

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 10-19

Practice 10-1 Overview


This practice covers the following topics: Importing an existing BC4J application into your project Extending an existing entity to include a new attribute Globally substituting extended entities and views for existing entities and views

Copyright Oracle Corporation, 2002. All rights reserved.

Instructor Note When the students import the Business Components application into their project, they must select the onlineorders.jar file and drill down into the .jar file. The JDeveloper import wizard automatically opens the file as if it were just another directory. After they have opened the .jar file, they then select the OnlineOrders.xml file to complete the import. The onlineorders.jar was created as a simple deployment of a BC4J project. It simulates receiving a project from a vendor or other development group. It is important to note that the students can enhance the application without knowing the details of the application.

Oracle9i JDeveloper: Develop Applications with BC4J 10-20

Practice 10-1 Start JDeveloper, and open the practice10.jws workspace. Take an existing BC4J application and extend it to use a new attribute in the Orders table. 1. Set up a custom environment. a. Run the customize.sql script: right-click BC4J database connection and select SQL Worksheet. Open the customize.sql file with the code editor and copy the SQL statement. Paste the statement into the SQL Worksheet and click the Run button. This will add a new column, ship_date, to the Orders table. b. You can expand the BC4J connection node to make sure the new column is in the Orders table. 2. Add OnlineOrders.jar to the project libraries. a. Edit the Extend.jpr project settings. b. Create a new library named OnlineOrders that points to <JDevHome>\mywork\OnlineOrders\OnlineOrders\OnlineOrde rs.jar. 3. Import the OnlineOrders classes into your project. a. Right-click the Extend project and select Import Business Components. b. Use the selection wizard to drill down into the OnlineOrders.jar file from <JDevHome>\mywork\OnlineOrders\OnlineOrders\ c. Select OnlineOrders.xml from the within OnlineOrders in the .jar file. d. Test the imported application with the Business Components Browser. 4. Extend the Orders entity to include a new attribute. a. Create a new package in the Extend project named extend. Do not create entity objects, view objects, or an application module for this package. b. Create a new application module that extends the OnlineOrders application module. c. Test the new module to see that it reflects the original OnlineOrders application module. d. Create a NewOrders entity that extends OnlineOrders.Orders. In the last step of the Entity Wizard, select Create Default View. e. Add the NewOrders view to the data model of your new application. f. Test the new application module using the Business Components Browser. Notice the difference between the old OrdersView and the NewOrders object. 5. Substitute the NewOrders and OrdersView objects globally. Now that you have made and tested the changes to the NewOrders entity, globally substitute it for all the occurrences in the original application. a. Edit the Extend project by right-clicking the project node and selecting Edit. b. Substitute the NewOrders entity for the Orders entity in OnlineOrders c. Substitute the NewOrders view for the Orders view in OnlineOrders. d. Test the application using the Business Components Browser. Notice that all occurrences of the CustomersView now reflect the new attribute ShipDate.

Oracle9i JDeveloper: Develop Applications with BC4J 10-21

Deploying Business Components Applications

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 60 minutes 60 minutes 120 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Describe n-Tiered Business Components architecture Describe the options for deploying a business components application Create deployment profiles Deploy a business components application as a middle-tier or server application Test a business components application deployed as an EJB

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim In previous lessons, you ran your application modules on your client machine, either through the Business Component Browser or by using simple Java test programs. In this lesson, you learn how to deploy a business components application for use in a production environment. You will see that JDeveloper9i takes care of most of the complexities of deployment for you.

Oracle9i JDeveloper: Develop Applications with BC4J 11-2

Overview

RMI/IIOP

JDBC

HTTP

Oracle9i EJB server Servlet-capable Web server


Copyright Oracle Corporation, 2002. All rights reserved.

Overview There are several ways to deploy a business components application module. Here are the more common ways: As an EJB session Bean on an EJB server, such as Oracle9iAS On a Web server, accessed through a servlet or JSP On a client machine. JDeveloper generates the necessary code for the deployment method that you choose. You do not have to make any changes to the application code based on the deployment method you choose. Instructor Note EJBs are covered in detail in the Develop Applications with Enterprise JavaBeans course. If students are interested in additional Java training, you can point them to the Java Training datasheet, which they can view by selecting Help > Oracle Java Education from JDevelopers main menu.

Oracle9i JDeveloper: Develop Applications with BC4J 11-3

n-Tiered Business Components Architecture


Four separate logical tiers at design time
Client code Web tier Business logic Database

Can be deployed in multiple physical configurations BC4J is tier independent Can be deployed to any Java platform without changes to your code

Copyright Oracle Corporation, 2002. All rights reserved.

n-Tier Business Components Architecture When you develop a business components application, you are really developing three separate logical tiers. At design time it is important to understand which tier performs which functions in you application. At deployment, each of the distinct logical tiers may be deployed in a number of ways. The logical boundaries can become a bit overlapped. For instance, client code may appear in any Java enable tier. It can be deployed to a traditional desktop PC, or as a JSP or even as a Enterprise JavaBean. In addition, the BC4J application is completely tier independent and can be deployed to any Java enable tier without changes to your business components or client code. Here are some common deployment models: Client Code Business Components On client machine On client machine On client machine As an EJB session bean or CORBA server object Servlet/JSP in a Web module In the Web module Servlet/JSP in a Web module As an EJB session bean or CORBA server object When business components are deployed as an EJB session bean or CORBA server object, the configuration is called remote deployment. Tier independence means that you can switch between remote deployment and deployment as a Web module or client machine without any changes to your code.
Oracle9i JDeveloper: Develop Applications with BC4J 11-4

Deployment Modes
Local:
BC4J components and Java clients share a JVM Is deployed as a J2EE archive

Web module:
BC4J components and Java clients share a JVM Is deployed as a J2EE archive Runs in an application server

Remote:
Separate JVMs for Java client and BC4J components Is deployed with a remotable interface Client access BC4J components is through IIOP
Copyright Oracle Corporation, 2002. All rights reserved.

Deployment Modes There are two basic modes for business components deployment: local mode and multitier mode. Local Mode In local mode, the BC4J components run in the same JVM as their clients, usually on a desktop PC client. Web Module In Web module mode, the BC4J components run in the same JVM as their client applications. Business components are deployed as standard J2EE-compliant files which client applications can access. This system is simpler, and communication between the clients and business components is faster than the traditional client-server, but the computational work of the business logic is in the same JVM as the client. Web module mode is generally the best choice for JSPs and servlets, which run on fast, shared machines.

Oracle9i JDeveloper: Develop Applications with BC4J 11-5

Deployment Modes (continued) Remote Mode In Remote mode, the BC4J components are deployed to a separate JVM from the Java client programs. They can be deployed as an Enterprise JavaBeans or as CORBA server objects. Before deployment, you give the application module remote capabilities, creating an EJB remote interface and client-side proxies for application module methods, which must be deployed to the Java client JVM. Client programs communicate with the business components through an IIOP connection. This system is more complex and requires an extra step in communication, but it allows business logic to be computationally separated from application logic.

Oracle9i JDeveloper: Develop Applications with BC4J 11-6

Local Deployment
The Java client runs in the same Java Virtual Machine (JVM) as the BC4J components application.

Application runs on a client machine

JDBC Oracle9i

Copyright Oracle Corporation, 2002. All rights reserved.

Local Deployment In this type of deployment, the Java client runs in the same JVM as the business components application module. This does not necessarily mean that the application module runs on a client machine. There are several deployment models that fit the local deployment description, such as: A batch program accessing the application modules view objects A fat client application, in which the business components reside on the client machine and are accessed through a Java GUI client

Oracle9i JDeveloper: Develop Applications with BC4J 11-7

Creating a Local Deployment

Copyright Oracle Corporation, 2002. All rights reserved.

Deploying a Local Application A local deployment is one in which the BC4J application components are included in a single Java Archive (.jar) file. You would then deploy that file to the machine that will host the JVM under which the application will run. To create a simple .jar file, first create a deployment profile for a simple archive. Start be right-clicking the project node in the navigator and selecting New from the shortcut menu. Next select Deployment Profiles from the New gallery. Select Jar File Simple Archive. This will prompt you to save the deployment profile. After you save the profile, you will see the Deployment Profile Settings Wizard. In this Wizard, select the files you want to include in the .jar file. All of the files are selected by default. If you want to include the source files and the compiled output files, select that option at the bottom of the page. For an explanation of all the options, please check the online documentation.

Oracle9i JDeveloper: Develop Applications with BC4J 11-8

Web Module Deployment


Used for deploying BC4J components to a Web tier Contains BC4J components and JSPs and servlets Used for deploying JSP and Servlet applications Deployment is to a J2EE .war file JDeveloper9i creates .war file and deployment descriptors

Copyright Oracle Corporation, 2002. All rights reserved.

Web Module Deployment This type of deployment is used for deploying BC4J applications to a middle tier, or an application server such as Oracle9iAS. The deployment usually contains the business logic application and the JSP or servlet application. This means that the deployment file, a .war file, contains all of the BC4J code and JSP or servlet code. JDeveloper9i provides complete deployment in this model and creates all the parts necessary for Web module deployment automatically. This deployment model has the business logic tier and client tier sharing the same JVM, which is hosted by an application server.

Oracle9i JDeveloper: Develop Applications with BC4J 11-9

Creating a Web Module Deployment


Web Module deployment combines
BC4J application components JSPs and servlets

Is deployed to an application server Use a WAR file: J2EE Web Module deployment profile

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Web Module Deployment A Web module deployment is a standard J2EE deployment model designed to be deployed to an application server such as Oracle9iAS. It contains all of the components of the business logic layer and JSPs or servlets. The deployment is created as a .war file which is a Web Archive file. The next few pages outline the steps in creating and deploying a Web module.

Oracle9i JDeveloper: Develop Applications with BC4J 11-10

Creating a Web Module Deployment

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Web Module Deployment Creating a Web module deployment is like creating any other deployment. First, you create a new deployment profile by selecting Deployment Profiles and WAR File J2EE Web Module from the New gallery. After you name and save the profile, JDeveloper launches the War Deployment Profile Settings Wizard. The default setting for the profile select all of the client JSP code, in our example, and all of the BC4J components.

Oracle9i JDeveloper: Develop Applications with BC4J 11-11

Creating a Connection to an Application Server


Start the Application Server Connection Wizard by
Right-clicking Connections > Application Server Click New Connection

Enter the following:


Connection name Connection type Username and password URL Target Web site

Test the connection

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Connection to An Application Server Before you can use the JDeveloper built in deployment utility, you must create a connection object. This connection is used by the deployment wizards to build the .war files and physically copy the deployment files to the target environment. You start the process by right-clicking the Application Server node under Connections in the Project Navigator pane. This launches the Connection Wizard. Enter the required information into the Wizard such as: Connection name Connection type (Oracle9iAS or WebLogic 6.x) Administrative username and password for the application server URL defaults to local host:default rmi port Target Web site where you want your application files to be deployed

Oracle9i JDeveloper: Develop Applications with BC4J 11-12

Deploying a Web Module


Right-click the deployment profile Click Deploy to Select a connection

Copyright Oracle Corporation, 2002. All rights reserved.

Deploying a Web Module Now that you have created a deployment profile and a connection to an application server, the rest of the process is almost automatic. To actually deploy the application, right click the deployment profile, click Deploy to and select the connection you want to use. JDeveloper will now use the connection information to copy the required deployment files to the target environment.

Oracle9i JDeveloper: Develop Applications with BC4J 11-13

Remote Deployment
An Enterprise JavaBean (EJB) or CORBA object deployed to Oracle9iAS An EJB deployed to an EJB server A CORBA object to a CORBA server Built-in deployments for:
Oracle9iAS: EJB WebLogic 6.x: EJB VisiBroker : CORBA

Copyright Oracle Corporation, 2002. All rights reserved.

Remote Deployment There are several platforms that support multitier deployment. The fundamentals of deployment to each of these platforms are the same. During the deployment process, you select the type of deployment you are using and JDeveloper9i creates the required Java classes and interfaces to support the deployment. This process is called making an application module remotable. JDeveloper9i has built-in deployment options for deploying a BC4J application to Oracle9iAS or WebLogic 6.x. It also supports the option to deploy to VisiBroker as a CORBA sever object.

Oracle9i JDeveloper: Develop Applications with BC4J 11-14

What Is a Remotable Application Module?


An application module that can be accessed from an object running in a different JVM

ClientOrdModule ordMethod() Client

OrdModuleImpl ordMethod() Server

Copyright Oracle Corporation, 2002. All rights reserved.

Accessing Application Modules Remotely You can access certain types of application modules remotely; for example, you can access some application modules from an object running in a different Java Virtual Machine (JVM) by using normal method calls. An application module that you can access remotely is also called a remotable application module. After you have designed your remotable application module and have deployed it, any client code that you write does not need to use any complex communication protocols. The following points provide a high-level view of running a application module with remote access: The remote application module, OrdModuleImpl, contains a method called ordMethod(). The client instantiates a local application module called ClientOrdModule, which contains the same method signatures as the remote application module. When the client code calls ClientOrdModule.ordMethod(), the remote method, OrdModuleImpl.ordMethod(), is executed. This happens through a series of interfaces and is transparent to the programmer who codes the client. JDeveloper creates the interfaces for you when you make the application module remotable. We will cover making the application module remotable in the next few pages.
Oracle9i JDeveloper: Develop Applications with BC4J 11-15

The Basic Architecture


Client and server modules implement the same interface. JDeveloper generates all the code.

ClientOrdModule implements OrdModule ordMethod()

OrdModuleImpl implements OrdModule ordMethod()

Stub Client

Skeleton Server

Copyright Oracle Corporation, 2002. All rights reserved.

The Basic Architecture In the example, you created an application module called OrdModuleImpl. During the deployment process, JDeveloper generates the following: An interface called OrdModule with method stubs that match all the exported methods in OrdModuleImp. A new declaration in OrdModuleImpl.java, making OrdModuleImpl a class that implements the OrdModule interface. A client application module class, ClientOrdModule, that also implements the OrdModule interface. Stub and skeleton code. The stub is a class that translates remote method calls into network communication setup and parameter passing; the skeleton accepts network connections from the stub and translates them into method calls on the remote application module. Because the local and remote application modules both implement the same interface, an instance of one class can be cast to an instance of the other. A key element in this remotable discussion is that JDeveloper9i creates all of the interfaces and uses them without requiring changes to your user written code. The process is truly transparent to the programmer.
Oracle9i JDeveloper: Develop Applications with BC4J 11-16

Making an Application Module Remotable

Copyright Oracle Corporation, 2002. All rights reserved.

Making an Application Module Remotable Before you can deploy an application module remotely, you must make it remotable.. To make it remotable, edit the application module and select the Remote tab. Next, select the type of deployment. The available types are: AppModule Session Bean (BMT): This option generates the code necessary to deploy a remote application module to Oracle 9iAS as an application module session bean with bean-managed transactions. This option allows the Session bean to manage the transaction. This option is the most simple and should be used in most cases AppModule Session Bean (CMT): This option generates the code necessary to deploy a remote application module to Oracle 9iAS as an application module session bean with container-managed transactions. This option allows you to share a single transaction across multiple application modules and allows the container to manage the transaction. Service Session Bean (BMT): This option generates the code necessary to deploy a remote application module to Oracle 9iAS as a service bean with bean-managed transactions. Service Session Bean (CMT): This option generates the code necessary to deploy a remote application module to Oracle 9iAS as a service bean with container-managed transactions.
Oracle9i JDeveloper: Develop Applications with BC4J 11-17

Making an Application Module Remotable (continued) CORBA Server for VisiBroker: This option generates the code necessary to deploy a remote application module to VisiBroker. For more information see About Container-Managed and Bean-Managed Transactions in the Help documents.

Oracle9i JDeveloper: Develop Applications with BC4J 11-18

Creating a Remote Application Module Deployment


Select New > Deployment Profiles > Business Components EJB Session Bean Profile. JDeveloper creates a profile and a configuration.

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Remote Application Module Deployment You create a deployment profile for a Remote Application like you do for any other deployment type. The difference is what JDeveloper does for you. Along with creating the .ear file that contains the business components, JDeveloper creates a application configuration file. This configuration file is used to manage connection information along with a number of parameters that control the behavior of the application module. It also provides an easy way to test the deployment using the Business Components Tester.

Oracle9i JDeveloper: Develop Applications with BC4J 11-19

Creating a Remote Application Module Deployment


Select AppModule Session Bean (BMT) Select Create AppModule Configurations

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Remote Application Module Deployment After you select Business Components EJB Session Bean Profile as the type of new deployment profile, JDeveloper launches the Business Components EJB Deployment Wizard. This Wizard allows you to choose which type of EJB deployment you want to use. For most cases, you should choose AppModule Session Bean (BMT), which stands for Bean Managed Transaction. This option allows the bean instead of the container to manage the transaction. The other options allow the container to manage the transaction and can therefore share a transaction across multiple application modules. This option is useful in some cases but requires complicated configuration to properly use a shared transaction.

Oracle9i JDeveloper: Develop Applications with BC4J 11-20

Deploying a Remote Application Module


Right-click the deployment profile Select Deploy JDeveloper deploys the necessary files to the EJB container

Copyright Oracle Corporation, 2002. All rights reserved.

Deploying a Remote Application Module Deploying a remote application module is similar to deploying any application module. Simply right-click the deployment profile and select Deploy. JDeveloper will now compile all of the required files, create the appropriate .jar and .ear files, and copy them to the application server.

Oracle9i JDeveloper: Develop Applications with BC4J 11-21

Testing a Remote Application Module Using the BC4J Tester

Copyright Oracle Corporation, 2002. All rights reserved.

Testing a Remote Application Module Using the BC4J Tester You can easily test your remote EJB deployment using the built-in BC4J Browser. Launch the tester by right clicking the application module and selecting Test. The first step in running the Browser is to select a connection type. JDeveloper created a configuration specific for the EJB deployment, so you can choose that configuration for this test. By choosing that configuration, the Browser will connect to the remote EJB deployment of the application module. The result is that you can use the BC4J Browser to test multiple configurations and deployments without having to write any code.

Oracle9i JDeveloper: Develop Applications with BC4J 11-22

Summary
In this lesson, you should have learned how to: Describe the options for deploying a business components application Create deployment profiles Create a remotable application module Deploy a business components application as a middle-tier or server application Use the BC4J Tester to test an EJB deployed to Oracle9iAS

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 11-23

Practice 11-1 Overview


This practice covers the following topics: Deploying a remotable application module as an EJB Testing the deployed application

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 11-24

Practice 11-1 Create a new BC4J application deploy it to Oracle9iAS. To start this practice: Start JDeveloper, and open the practice11.jws workspace. 1. Create a new BC4J application. a. Create a new project containing a new BC4J application. Name the project Deploy. Select Customers, Orders, Order_Items, and Product_Information as the entity objects for this project. b. Modify the application in anyway you like. For example, you could exclude some of the columns from a default view or add some specific business logic. c. Build, save, and test your application using the Business Component Browser. 2. Install and start oc4j. Before you can deploy applications to OC4J, you must install the product. This is a very simple procedure which sets the password for the administrator account (admin). a. Open a command window by clicking Start -> Run from the windows Task bar. b. Change directories to <JDev Home>j2ee\home, where <JDev Home> is the installation directory for JDeveloper. Enter the command cd <JDev Home>j2ee\home c. Once you are in that directory, enter the command: java -jar oc4j.jar install d. Enter admin as the password for the administrator account. The install tool will ask you to enter it again. e. After the installation is complete, which should take only seconds, start the oc4j server by entering the following command: java jar oc4j.jar 3. Create a connection to the application server. a. Right-click the application server node under Connections in the navigator and select New Connection from the context menu. b. Name the connection OC4J. c. Use admin as the username and admin as the password. This should be the same password that you used in step 2. d. Use the defaults for the rest of the properties and test the connection. If it tests successfully then continue to the next step. 4. Create a deployment profile for an EJB deployment. a. From the New Gallery, select Deployment Profiles > Business Components EJB Session Bean Profile. b. Make sure the server connection is the same as the connection you just created and select AppModule Session Bean (BMT) as the deployment style you want to use. c. In the next step of the wizard, select the application module you want to deploy with this profile and click finish. 5. Make your application module remotable. In this step, you modify your application module so that JDeveloper will create and manage all of the classes necessary to make this application remotable. a. Edit the application module b. Select the Remote tab and make the module remotable. c. Select AppModule Session Bean (BMT) as the remotable style for this application module and click OK.
Oracle9i JDeveloper: Develop Applications with BC4J 11-25

Practice 11-1 6. Deploy your application module to Oracle9iAS. a. Right-click the deployment profile you just created. b. Select Deploy from the context menu. c. JDeveloper will launch the necessary commands to deploy your application as an EJB Session Bean to the Oracle9iAS server. You can watch the commands and resulting messages in the Log window at the bottom of the JDeveloper IDE. 7. Test your deployed application using the Business Components Browser. a. Launch the tester as usual. b. Select DeployModule9iAS as the Business Components Configuration Name at the top of the Connect page of the tester. This will tell the tester where your application is deployed and how to connect. c. Click connect. d. Test your application as usual. e. Close the tester.

Oracle9i JDeveloper: Develop Applications with BC4J 11-26

Creating Batch Clients and XML for a Business Components Application

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 60 minutes 45 minutes 105 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Create a batch client for a business components application Use BC4J methods to create an XML document for a view object

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim In this lesson, you should learn how to create a client for a business components application. You should also learn how to create an XML document from a BC4J View object. This is useful when you want to exchange data between applications using Java Message Service (JMS).

Oracle9i JDeveloper: Develop Applications with BC4J 12-2

Overview
Java client BC4J Server Application RMI/IIOP JDBC

HTTP Servlet Web server

HTML client

Copyright Oracle Corporation, 2002. All rights reserved.

Overview A BC4J application running in a server can be accessed from any number or types of client applications. The client for your application can be HTML, Java GUI, or a non-GUI client. The nature of the BC4J framework allows you to access your application as the business logic layer from any type of client..You do not have to change your application module to run with different clients.

Oracle9i JDeveloper: Develop Applications with BC4J 12-3

Creating a Batch Client


Retrieve a BC4J application module from the context factory. Find and instantiate a view object. Find and manipulate data from the view object. Release the application module.

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a Batch Client When you want to create a Java client without a graphical user interface, you need to handcode your client. Hand-coded or batch clients are useful for batch processing or for a client driven by a command-line interface. The procedure for hand-coding clients is almost the same for any application module deployment configuration. The first step is to retrieve an application module from a context factory. You do this by calling the Configuration class and using the BC4J configuration that is automatically generated in JDeveloper9i. This class handles all of the connection details required to find and retrieve an application module. After you retrieve an application module, the next steps depend on what you want to do in your batch client. For our example we will be instantiating a view object and then manipulating some of the data in the view object. The last thing we will do in our batch program will be to release to application module.

Oracle9i JDeveloper: Develop Applications with BC4J 12-4

Instantiating an Application Module


Instantiate the application module using the Configuration class. Use the fully qualified application name and the configuration name as arguments.
String _am String _cf // App module name = "OnlineOrders.OnlineOrdersModule"; // Configuration name = "OnlineOrdersModuleLocal";

// Create an instance of the AppModule ApplicationModule am = Configuration.createRootApplicationModule(_am,_cf);

Copyright Oracle Corporation, 2002. All rights reserved.

Instantiating an Application Module JDeveloper9i provides a Configuration class that manages all of the requirements for finding and instantiating a BC4J application module. This class uses the name of the application module the the name of the configuration as parameters. The configuration file in JDeveloper9i keeps all of the connection information necessary to perform an JNDI lookup and create an Application module. For more information about the Configuration class, consult the JavaDoc included in JDeveloper9i. To find and create an application module, call Configuration.createRootApplicationModule(), passing it the fully qualified application module name along with the name of the BC4J configuration. This method returns an Application module instance. Instructor Note If students want a deeper understanding of how JNDI works, they can refer to the following Web sites. Sun has published a JNDI tutorial, which is located at the following URL: http://java.sun.com/products/jndi/tutorial The javadoc for the JNDI packages is located at the following URL: http://java.sun.com/products/jndi/1.2/javadoc
Oracle9i JDeveloper: Develop Applications with BC4J 12-5

Finding and Instantiating a View Object


Access data from View Objects. Use findViewObject() to find and instantiate the view object.
// App module name = "OnlineOrders.OnlineOrdersModule"; // Configuration name = "OnlineOrdersModuleLocal";

String _am String _cf

// Create an instance of the AppModule ApplicationModule am = Configuration.createRootApplicationModule(_am,_cf); ViewObject vo = am.findViewObject("CustomersView");

Copyright Oracle Corporation, 2002. All rights reserved.

Finding and Instantiating a View Object The application module that you instantiated in the previous step manages the view objects you added to the data model at design time. These view objects are the components that are exposed to the client for data access. To access data from the application module, instantiate a ViewObject. You do this by using the findViewObject() method of the application module. This method returns a view object that you can use to return, display, and manipulate data.

Oracle9i JDeveloper: Develop Applications with BC4J 12-6

Finding Data by a Primary Key


Check the command line argument. Create an oracle.jbo.Key object. Call findByKey() which returns an array of Row objects.
if (args.length==0) { system.out.println("Customer ID is required"); System.exit(0); } Key custKey = new Key(new Object[] {args[0]}); Row[] customers = vo.findByKey(custKey,1);

Copyright Oracle Corporation, 2002. All rights reserved.

Finding Data by a Primary Key When creating a batch program that retrieves data, you will probably accept a runtime argument to help select specific data. The first thing you should do is check that the argument has been supplied. If it has not, you simply display a message and exit the program. You use the findByKey() method to find and return specific rows from a view object. This method accepts two arguments. The first is a oracle.jbo.Key object and the second is the maximum number of rows to return. The result of findByKey() method is an array of Rows. Once this method is successful, you can parse through the Row[] array and manipulate the data.

Oracle9i JDeveloper: Develop Applications with BC4J 12-7

Manipulating the Data


Check the Rowset for data. Create a row from the Rowset. Call getAttribute() on the row object to display data.
if (customers.length==0) System.out.println("Customer not found"); } else Row row_Cust = customers[0]; } System.out.println("Customer Last Name: " + row_Cust.getAttribute("CustLastName"));

Copyright Oracle Corporation, 2002. All rights reserved.

Manipulating the Data Before you can manipulate the data in the Row[] array, you need to make sure that the findByKey() retrieved some data. You do that be checking the length of the array. Check to see that customers.length() is greater than zero. If it is, then you know you have retrieved at least one row. When you know you have at least one row in the array, you can create a single row object to hold a row from the array. It is this object you will be manipulating. Once you have a single row object, you can then call the getAttribute() method. This method takes a string as an argument and returns a string. The string argument needs to be one of the attributes defined in the View object. By creating a Row object from the array, you have access to all of the generic Row methods like: getAttribute(), setAttribute(), getAttributeCount(), getAttributeIndexOf(), isAttributeUdpdateable(), and so on.

Oracle9i JDeveloper: Develop Applications with BC4J 12-8

Calling Custom Methods


Cast the Row Array object to a view object. Call the custom method on the view object.

if (customers.length==0) System.out.println("Customer not found"); } else CustomersViewRow row_Cust = (CustomersViewRow)customers[0]; } System.out.println("Customer Full Name: " + row_Cust.getCustFullName());

Copyright Oracle Corporation, 2002. All rights reserved.

Calling Custom Methods When you use the generic Row class to hold the data from the view object, you only get access to the generic row handling methods. Although these methods give you access to the data, you can't access any custom methods you may have coded in the view object class. To access those methods, you need to cast the Row object to the specific View Object Row class. In our example the class is CustomersViewRow. Once the generic Row is cast to a CustomersViewRow object, you can call any of the custom methods. Those methods include getter and setter methods for each of the attributes along with any special methods you may have created.

Oracle9i JDeveloper: Develop Applications with BC4J 12-9

The Sample package BatchClient; import OnlineOrders.common.*; import oracle.jbo.*; import oracle.jbo.client.Configuration; public class TestClient2 { public static void main(String args[]) { String _am = "OnlineOrders.OnlineOrdersModule"; String _cf = "OnlineOrdersModuleLocal"; if (args.length==0) { System.out.println("Customer ID is required"); System.exit(0); } ApplicationModule am = Configuration.createRootApplicationModule(_am,_cf); ViewObject vo = am.findViewObject("CustomersView"); Key custKey = new Key(new Object[] {args[0]}); Row[] customers = vo.findByKey(custKey,1); if ( customers.length == 0 ) { System.out.println("Customer not found "); System.exit(0); } else { Row row_Cust = customers[0]; System.out.println("Customer Last Name: " + row_Cust.getAttribute("CustLastName")); } Configuration.releaseRootApplicationModule(am,true); } }
Oracle9i JDeveloper: Develop Applications with BC4J 12-10

JDeveloper9i and XML


Each component in BC4J is made of both Java and XML. Declarative Entity validation rules are stored as XML. Domain definitions are stored as XML. Column to attribute mappings are stored as XML. The BC4J Framework reads the XML for metadata and validation when required.

Copyright Oracle Corporation, 2002. All rights reserved.

JDeveloper9i and XML JDeveloper uses XML to organize your project contents. Further, business rules (such as validation rules) are stored in XML rather than Java source code. This use of XML allows JDeveloper9i and BC4J flexibility in design and deployment. Because the XML is used at run time, some modifications to the application can be made at run time by using the XML meta data.

Oracle9i JDeveloper: Develop Applications with BC4J 12-11

What Is XML?
A markup language annotates (or marks up) some text. XML is a markup metalanguage. It enables you to define your own language. It defines rules about how you can mark up a document. You can use it to extend your language if necessary. HTML is a markup language that does not obey the rules of XML.

Copyright Oracle Corporation, 2002. All rights reserved.

What Is XML? XML is defined as a markup metalanguage. XML is a language that attempts to be selfdescribing. The key aspect in XML is that it enables you to define your own language. For instance, you might want to store information about (online) orders made to your company in a database such as Oracle. But the database data is digested by the SQL interpreter, and therefore it is best to store it in a binary form friendly to computer logic. You might want to store the information as a text file or an HTML file. But then only a browser can understand the information. If a department other than yours in your company wants to access information, you will have to explain how you have organized the data in your database schema or your HTML text. The information is not self-describing. If, on the other hand, you can invent your own language and use tags such as Order-Quantity to describe your data, then it is easier for a computer program to look at the data and figure out what the data is all about. This is much the same as when you can look at a bunch of numbers with the keyword Beginning-Balance and you believe that the data is some sort of financial data. By defining your own language, and by having the capability to extend the language, you also protect your effort for the future. HTML was and is useful to a computer program to figure out how to display data. XML is useful to a computer program to figure out what the data is all about. The key is to enable you develop your own custom language.
Oracle9i JDeveloper: Develop Applications with BC4J 12-12

XML Syntax Rules


XML documents: Start with an XML declaration Contain empty and nonempty tags Empty tags end with /> Nonempty tags
Usually contain more information than empty tags Must match and nest properly and attribute names are case sensitive

Include a unique opening and closing tag that contains the whole document (the ROOT element) Contain attributes (values must be in quotes)

Copyright Oracle Corporation, 2002. All rights reserved.

XML Syntax Rules XML documents are free formatted (like HTML). You can freely place white space. However, there are a few rules: XML documents must start with a prolog (or preamble). The minimum preamble is <?xml version="1.0"?>. Tags in an XML document must match. For example, if you have a tag such as <employeenumber>, it must be followed by the tag </employeenumber>. Tags in an XML document must nest correctly. For example, the sequence <customer> <name>Jane Daux</name> <company>Jane's Fine Foods Inc.</company> <status> Active</status> </customer> is nested properly because the <name> tag is not interspersed with the <company> tag, and both of them are contained in the <customer> tag.

Oracle9i JDeveloper: Develop Applications with BC4J 12-13

A Customer Example
Markup reflects the structure of the information. Markup is specific to a particular application domain.
<customer> <name>Jane Daux</name> <address> <street>100 Main St.</street> <city>Anytown</city> <state>Texas</state> <postalcode>77034-4518</postalcode> </address> </customer>

Copyright Oracle Corporation, 2002. All rights reserved.

A Customer Example The slide shows an example of a simple XML page. Note the use of tags, a piece of text that describes a unit of data. Tags are distinguishable as markup rather than data because they are surrounded by angle brackets (< >). Note also the use of tags that describe the data. Clearly address (as opposed to addr or ad) stands for something meaningful. You could have stored the data as the following HTML text but it would not have the same information as the XML text. Suppose you were to send this data to a partner, such as a Human Resources payroll firm. The partners computer program is unlikely to be able to make sense of the HTML text, whereas it would be easier to make sense of the XML text. (It would be harderfor a computer programto figure out that 77034-4518 represents a postal code.) Since XML text must always be well formed, there are no misplaced tags in the XML document. If this were an HTML document, it may have misplaced or even incorrect tags.

Oracle9i JDeveloper: Develop Applications with BC4J 12-14

The BC4J Project XML File


<?xml version="1.0" encoding='windows-1252'?> <!DOCTYPE JboProject SYSTEM "jbo_03_01.dtd"> <JboProject Name="Project10" TimeStamp="1011035129140" SeparateXMLFiles="true" PackageName="" > <DesignTime> <Attr Name="_version" Value="9.0.2.7.17" /> <Attr Name="_jprName" Value="../Project10.jpr" /> <Attr Name="_NamedConnection" Value="adt" /> </DesignTime> <Containee Name="mypackage10" FullName="mypackage10.mypackage10" ObjectType="JboPackage" > </Containee> </JboProject>

Copyright Oracle Corporation, 2002. All rights reserved.

The BC4J Project XML File JDeveloper9i uses XML for its own metadata. When you create a project, JDeveloper9i creates an XML file with the extension .jpx. It uses the file to manage design time elements such as connection information and file locations.

Oracle9i JDeveloper: Develop Applications with BC4J 12-15

XML Structure
Prologue:

XML declaration DTD Processing


Root element Epilogue:

<?xml version="1.0" encoding='windows-1252'?> <!DOCTYPE JboProject SYSTEM "jbo_03_01.dtd">

instructions and comments


<JboProject </JboProject> <?gifPlayer Size="100,300" ?>

Processing instructions and comments

Copyright Oracle Corporation, 2002. All rights reserved.

XML Structure As you can see, the prologue contains attributes. The encoding attribute identifies the character set used to encode the data. Windows-1252 is an English language character set used on Windows platforms. (The default is compressed Unicode: UTF-8.) This document specifies a Document Type Definition (DTD). The DTD specification is an optional part of the XML specification and has its own syntax.. The DTD specifies what elements are required and optional within an XML document. If an XML document specifies that it uses a particular DTD, then the document must conform to the definitions within that DTD. It has two parts: The SYSTEM keyword specifies the location of the DTD file. Since it does not start with a prefix such as ftp:/ or http:/, the path is relative to the location of the XML document or a default location (in JDeveloper, the DTD is in jdev\bc4j\lib\bc4jmt.zip and in the package oracle.jbo.dtd). The DOCTYPE keyword indicates which element being described in the current XML file needs to be validated against the DTD. In this example, it is the ROOT element JboProject. The DOCTYPE tag occurs after the XML declaration and before the root element.

Oracle9i JDeveloper: Develop Applications with BC4J 12-16

XML Structure (continued) An XML file can also contain processing instructions that give commands or information to an application that is processing the XML data. Processing instructions have the format <?target instructions?>, where the target is the name of the application that is expected to do the processing, and instructions is a string of characters that embodies the information or commands for the application to process.

Oracle9i JDeveloper: Develop Applications with BC4J 12-17

Using BC4J to Output XML


XML is useful to exchange information between applications. BC4J provides methods to output view object data as XML. You can output XML data from any view object.

Copyright Oracle Corporation, 2002. All rights reserved.

Using BC4J to Output XML One of the benefits of XML is the ability to exchange data between disparate applications. You can use XML to connect legacy systems to new Java based applications. BC4J provides methods to read, write, and parse through XML documents. These methods are accessible from any View object. The next few pages show you how to output XML from a view object.

Oracle9i JDeveloper: Develop Applications with BC4J 12-18

Using BC4J to Output XML


Start with an application that:
Retrieves an application module from the context factory Instantiates a view object

Call writeXML on the view object Cast the result to and XMLNode
XMLNode node = (XMLNode) vo_Cust.writeXML(0,0);

Copyright Oracle Corporation, 2002. All rights reserved.

Using BC4J to Output XML (continued) The steps to write XML from a View object start the same as any client application using a View object. You first instantiate an application module, then the View object you want to use. After you instantiate the View object, you can call the writeXML() method on the view object. This method renders the view object data in a canonical XML-format. The classes ViewObjectImpl and ViewRowImpl implement this method to render data in XML. Use this method whenever data is required in XML format, either to present a UI (after converting XML data into some HTTP format using a style sheet) or to pass the data as payload for messages via JMS. There are two parameters for this method. The first is the depthcount parameter which represents to what level the rendering should recurse. A depthcount of zero (0) means do not traverse any View Links while rendering. One (1) means traverse the View Links on this object but no View Links thereafter, and so on. The second argument is the options parameter which represents a set of bit flags that will control the writeXML behavior. There are several defined flags that determine if all rows of the rowset will be written or only those that have been changed. For now, the value of 0 writes all rows in the rowset.

Oracle9i JDeveloper: Develop Applications with BC4J 12-19

Using BC4J to Output XML


Create a ByteArrayOutputStream Call print() on the node object Convert the ByteArrayOutputStream to a string
OutputStream os = new ByteArrayOutputStream(); try { node.print(os); System.out.println(os.toString()); } catch (IOException ioex) { ioex.printStackTrace(); }

Copyright Oracle Corporation, 2002. All rights reserved.

Using BC4J to Output XML (continued) After you have created a node object from the View object rowset, you can now start to process to write the node to whatever device you choose. In our example, we will prepare it for a simple print to System.out.println(). The first step is to create an OutputStream to hold the results of the node.print() method. The node.print() method converts the XMLNode object into an OutputStream object. The node.print() method throws a java.io.IOException; must be caught or declared to be thrown, so the method must be placed in a try block. When the node.print(os) statement is successful, you can os the OutputStream anyway you like. In our example, we simply call use System.out.println() to send it the standard console.

Oracle9i JDeveloper: Develop Applications with BC4J 12-20

BC4J and Java Messaging Service


BC4J includes methods to pass messages to a queuing system. Message queuing is used to exchange data between dissimilar applications. You can send and receive any XML document. To send a document call sendMsgtoQueue() on the application module.
((OnlineOrdersModuleImpl) am.useApplicationModule()). sendMsgtoQueue(os.toString);

Copyright Oracle Corporation, 2002. All rights reserved.

BC4J and Java Messaging Service Sun Microsystems, Inc. provides a Java Message Service (JMS) API, that you can use with BC4J to implement XML Messaging. XML Messaging is a technique for exchanging data in a common format (XML) that can be parsed and used by any system that can read XML. The exchange of the data is handled through JMS. The applications involved in the exchange implement adapter classes that send and receive messages through the queue. As you have just seen, Business Components for Java includes methods to convert components to and from XML. Once the data is converted into XML it can be placed in a message queue. The applications involved in the exchange may be similar but more than likely are dissimilar in platform, language, or deployment. Whatever the case, you can exchange data and messages through Java Messaging Services(JMS). In our example, the message payload is the XML data derived from the original business data in the database. This message is routed to one or more destination systems, which reverse this process to store the data in the remote databases or are otherwise used by remote systems. The methods to send the message to the queue are executed on the current instance of the application module. You get the current instance by calling useApplicationModule(). You then call sendMsgtoQueue() passing it the OutputStream converted to the String object.
Oracle9i JDeveloper: Develop Applications with BC4J 12-21

BC4J and Java Messaging Service (continued) These are the basic steps used to send messages to the Message Queue. For further information and for an example, see the sample project in <JDeveloper installation directory>\BC4J\samples\OnlineOrdersForClients\MessagingClient.

Oracle9i JDeveloper: Develop Applications with BC4J 12-22

Summary
In this lesson you should have learned how to: Create a batch client for a BC4J application Find and instantiate a View object Navigate through a View object Create an XML document from a View object

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 12-23

Practice 12-1 Overview


This practice covers the following topics: Writing a hand-coded client for a deployed application module Navigating through the data of a View object Calling an application module custom method Converting a View object rowset to an XML document

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 12-24

Practice 12-1 Start JDeveloper, and open the Practice12.jws workspace. In this practice, you will code a batch client to run against the OnlineOrders application module. The BC4J application is already created and ready for you to access from a batch client. 1. Examine and test the OnlineOrders application module. a. Open the OnlineOrders project in the navigator. b. Open OnlineOrdersModuleImpl.java and look at the code for the method ordersWithLinesOverQuantity. This method is a custom application module method that can be called by any client that has access to the application module. c. Rebuild and test the Business Components Project OnlineOrders. 2. Create a new project with a batch client that instantiates the OnlineOrders application module. a. Create a new Business Components project and name it BatchClient. When the Business Components Wizard launches, you can click finish without selecting any tables for this project. You are creating this project as a Business Components project so that the necessary libraries are added by default. You could create a non-BC4J project but you would have to add the bc4j libraries manually. b. Create a new Application from the New Gallery. c. Name the application BatchClient. Do not include a default frame. d. Add import statements for: oracle.jbo.client.Configuration; oracle.jbo.*; OnlineOrders.common.*; e. Create a library named OnlineOrdersPath that points to the directory that holds the OnlineOrders classes. The path is <JDevHome>\jdev\mywork\OnlineOrders\OnlineOrders\classes. f. Add that library to your project. g. Replace the code "new BatchClient();" with your code to instantiate the OnlineOrders application module. The application name is OnlineOrders.OnlineOrdersModule. The configuration name is OnlineOrdersModuleLocal. h. Add a print statement at the end of the main() to display a success message when you successfully make it through the program. i. Save your changes, compile, and test your program. At this stage, your program does not pull any data from the database, but it should compile and run without error and display your success message. This proves that you were able to instantiate the application module. With that complete, you can begin to add code that will display data from the Business Components in the OnlineOrders application module.

Oracle9i JDeveloper: Develop Applications with BC4J 12-25

Practice 12-1 (continued) 3. Add code to instantiate a CustomersView object and display information about the first customer in the result set. a. Find and instantiate a CustomersView object. b. Retrieve the first instance of the CustomersView. c. Check to make sure the first row is not null. If it is null, print a message that the result set is null. d. Print the Customers Id, Name and Email address. e. Save, build, and run your program. 4. Add code to display all of the orders for the Customer you just retrieved. a. Instantiate a rowset of orders for the current customer. Use the OrdersView attribute of the customers row. b. Check to make sure the rowset is not null. If it is not null, loop through the result set displaying the Order ID, Order Date, Order Status, Order Total, and Order Mode for each Order. c. Save, build, and run your program. 5. Write the contents of the CustomersView object as an XML stream. a. Add import statements for: import oracle.xml.parser.v2.*; import java.io.*; b. Add code to create an XMLNode object from the CustomersView object you have already instantiated. c. Create a ByteArrayOutputStream object to hold the results of node.print(). d. Convert the OutputStream to a String and display the results to the standard output stream. e. Save, build, and run your program. f. Change the parameters to the writeXML() method to (1,1), which will display only one Customer but will traverse the link to show the Orders for that Customer. g. Save, build, and run your program. h. Change the parameters to (2,1) to see the LineItems for each Order. i. Save, build, and run your program 6. In an earlier lesson, you learned about custom methods you can add to an application module. These custom methods are useful to supply information to a client without requiring the client to instantiate any views. In this step you will use a custom method to display some business information. a. Before you can access custom methods in the application module, you must cast the generic application module to an OnlineOrdersModule. You do this in the code that instantiates the application module. You must also import the OnlineOrders.common.* classes. b. Create a long variable and set it equal to the result of the application module custom method ordersWithLinesOverQuantity(4). This method counts the number of OrderItems which have ordered quantities of more than 4. c. Save, build, and run your program. d. Change the parameter to the custom method and test again to see different results.

Oracle9i JDeveloper: Develop Applications with BC4J 12-26

Creating Custom and Dynamic Queries

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 45 minutes 75 minutes 120 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Create a view object that is based on a SQL statement Modify a view object's query at run time Instantiate a view object at run time

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim In previous lessons you should have learned how to create a view object based on one or more entity objects, and how to define the view object completely at design time. This lesson demonstrates different ways of creating and changing view objects. A view object does not have to be based on any entity objects, and its definition can be changed at run time. You can even create a new view object at run time.

Oracle9i JDeveloper: Develop Applications with BC4J 13-2

SQL-Based View Objects


A SQL-based view object:
Is not based on any entity object Cannot be used for insert, update, or delete

Use SQL-based view objects for query-only views, which do not need the functionality of entity objects.

Copyright Oracle Corporation, 2002. All rights reserved.

SQL-Based View Objects A SQL-based view object is based on a SQL query, not on any entity object. This type of view object is for query-only views; it cannot be used to update data. If you want to create a view object that is always query-only, you should create a SQL-based view object, because then you do not need the data-caching functionality that underlying entity objects provide. Instructor Note For query-only views, SQL-based view objects tend to give better performance than entitybased view objects.

Oracle9i JDeveloper: Develop Applications with BC4J 13-3

Creating a SQL-Based View Object


Create a view object without selecting an entity object in the View Object Wizard. Click the Query tab of the wizard and enter your query in the field provided.

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a SQL-Based View Object 1. In the Navigator pane, right-click the package name and select Create View Object from the Context menu. 2. In Step 2 of the View Object Wizard, click Next without selecting an entity object. The wizard goes straight to Step 5. 3. In Step 5 of the wizard, enter your query in the Query Statement field, and then click Finish.

Oracle9i JDeveloper: Develop Applications with BC4J 13-4

Expert-Mode View Objects


A view objects query has two modes:
Normal (the default): You can alter only the Where and Order By clauses of the query. Expert: You can alter any part of the query.

To select expert mode:


Click the Query tab

Select Expert Mode


Copyright Oracle Corporation, 2002. All rights reserved.

Expert-Mode View Objects Every view object uses a SQL query to retrieve its data. There are two possible modes for this query: normal mode and expert mode. All of the view objects that you have created in previous lessons have used normal mode. Normal-Mode View Objects JDeveloper generates the SQL query based on the view objects attributes. In normal mode, you can sort and filter the data by changing the Where and Order By clauses of the query, but you cannot change the Select clause of the query. In this way, JDeveloper keeps the query synchronized with the attributes in your view object. You can change the select using the Entity and Attributes tab, by selecting other entities and attributes. Expert-Mode View Objects Selecting the Expert Mode check box in the Query tabbed page of the View Object Wizard allows you to enter any valid SQL statement for your view objects query. Note that if you deselect the Expert Mode check box, the default query is regenerated and any changes you have made to the query are lost. You can create a View object that is not based on an entity object. These view objects are called SQL-based views. These views are considered special cases of expert mode view objects.
Oracle9i JDeveloper: Develop Applications with BC4J 13-5

Mapping Attributes in Expert Mode


In normal mode, JDeveloper maintains the correct mapping between entity attributes and database columns. Editing a query in expert mode may invalidate these mappings. For example, edit the CustomersView query:
SELECT ID, NAME, initcap(STATUS) AS Status FROM CUSTOMERS

At run time, the value of the Status attribute does not match the value in the underlying table. Performing an update with the view gives a locking error.
Copyright Oracle Corporation, 2002. All rights reserved.

Mapping Attributes in Expert Mode With a normal-mode view object, JDeveloper controls the Select clause of the SQL query. This allows JDeveloper to keep the correct mapping between entity attributes and database columns. Once you change your query to expert mode, JDeveloper may not be able to maintain the correct mapping. The preceding slide shows an example of an expert-mode query causing problems with attribute mapping. Instructor Note Explain how the query on the slide can cause problems: A database row with values 272, Channing, GOLD would be selected into the view object as 272, Channing, Gold. If you change this row at run time and try to commit the changes, the business components run time sees that the row in the database is not the same as the row that was originally selected, because Gold does not match GOLD. The run-time environment concludes that another user must have changed the database row after the row was last selected. This causes a locking error and changes cannot be committed.

Oracle9i JDeveloper: Develop Applications with BC4J 13-6

Maintaining Attribute Mappings in Expert Mode


You are responsible for maintaining the correct mapping between entity attributes and database columns. For the customer status example:
Delete the Status attribute from your view object. Create a new calculated attribute called Status.

Copyright Oracle Corporation, 2002. All rights reserved.

Maintaining Attribute Mappings in Expert Mode When you create an expert-mode query for your view object, you are responsible for maintaining the correct mappings between entity attributes and database columns. The slide shows how to do this for the example on the previous slide. You replace the Status attribute in your view object with a calculated attribute. This new calculated attribute maps to the alias that you defined in your expert-mode query; the attribute is now correctly mapped to the database. Instructor Note Stress that, in general, you should avoid using expert-mode queries based on entities if the view is used for updating, because of attribute mapping problems. SQL-based queries do not have these problems, however, and are useful in cases where you do not want to update through your view object.

Oracle9i JDeveloper: Develop Applications with BC4J 13-7

Setting Parameters for the Where Clause

The Where clause of a view objects query can contain either variables or parameters.
Use ? style parameters

status = ? and quantity > ?

status = :1 and quantity > :2

Use ? style parameters

At run time, you can assign values to the parameters.

Copyright Oracle Corporation, 2002. All rights reserved.

Setting Parameters for the Where Clause You do not have to specify a view objects query completely at design time. The preceding slide and the following slides show how to make a view object more dynamic. This slide shows how to give a view object a variable where clause. In the View Object Editor, click the Query tab and enter a parameterized value in the Where: field. There are two types of parameters that you can set for a Where clause: JDBC style, or ? style; if you use this style you must also select Use ? style parameters. Oracle style; this style allows you to use the same parameter more than once in a where clause, for example: quantity = :1 and backorder = :2 and :1 > :2 Assigning Values to the Parameters If your view object has a Where clause with parameters, you must assign values to the parameters, or your application will throw an exception. The following slide shows how to assign values to a Where clauses parameters at run time.

Oracle9i JDeveloper: Develop Applications with BC4J 13-8

Assigning Values to Queries with Parameters at Run Time


Here are two ways to assign parameters:

// lineVo is a ViewObject lineVo.setWhereClauseParam(0, "S"); lineVo.setWhereClauseParam(1, new oracle.jbo.domain.Number(10)); Object[] params = new Object[]{"S", new oracle.jbo.domain.Number(10)}; lineVo.setWhereClauseParams(params);

After assigning parameters, you need to execute the query again:

lineVo.executeQuery();

Copyright Oracle Corporation, 2002. All rights reserved.

Assigning Values to Parameterized Queries at Run Time The preceding slide shows how to assign values to Where clause parameters at run time: you can assign parameters individually or all at once. The syntax is the same whether or not you selected Use ? style parameters in the View Object Editor. Note that parameters are indexed, starting from 0. This may be a little confusing if you used number parameters in the View Object Editor. In the second code example on the previous slide, the Where clause is set as follows: status = :1 and quantity = :2 However, the following statement assigns a value to the second parameter (quantity): lineVo.setWhereClauseParam(1, new oracle.jbo.domain.Number(10)); If you change a Where clause's parameters, you must reexecute the query in order to update the cache with the new data. Note: To test using parameterized queries at run time, we need access to the runtime program. The BC4J browser that we have been using so far does not provide that programming environment. To demonstrate how to create and manipulate this query, we need to use a test client program. You will see how to build client programs later in this course.
Oracle9i JDeveloper: Develop Applications with BC4J 13-9

Setting Where and OrderBy Clauses at Run Time


To set a view objects Where clause:

// lineVo is a ViewObject lineVo.setWhereClause("status = 'P'");

To set a view objects Order By clause:

lineVo.setOrderByClause("quantity desc");

Copyright Oracle Corporation, 2002. All rights reserved.

Setting Where and Order By Clauses at Run Time You can change a view object's where clause completely; the preceding slide shows how to do this. As before, if you change a view object's Where or Order By clause, you must call executeQuery() to reexecute the view object's query.

Oracle9i JDeveloper: Develop Applications with BC4J 13-10

Creating a New View Object at Run Time


To create a new view object based on an entity:

//am is an ApplicationModule String entity = "orders.LineItem"; String selectClause = "id, status, quantity"; String fromClause = "line_item"; String whereClause = "status = 'S'"; ViewObject shippedItemsVo = am.createViewObjectFromQueryClauses(null, entity, selectClause, fromClause, whereClause, null);

To create a new view object based on a query:

ViewObject queryItemsVo = am.createViewObjectFromQueryStmt("", "select id, status, quantity from line_item");

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a New View Object at Run Time You can create a completely new view object at run time; the preceding slide provides sample code for this. Creating a View Object Based on an Entity Object The first example demonstrates how to create an entity-based view object by calling the method am.createViewObjectFromQueryClauses(). The first parameter is the view object name; in the example the name is null, so a system-generated name is assigned to the view object. The last parameter is the Order By clause, which is also null because there is no order by clause in this query. Creating a View Object Based on a Query The second example shows how to create a SQL-based view object by calling the method am.createViewObjectFromQueryStmt().

Oracle9i JDeveloper: Develop Applications with BC4J 13-11

Summary
In this lesson, you should have learned how to: Create a view object that is based on a SQL statement Modify a view objects query at run time Instantiate a view object at run time

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 13-12

Practice 13-1 Overview


This practice covers the following topics: Creating a SQL-based view object Creating a query with parameters

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 13-13

Practice 13-1 Start JDeveloper, and open the practice13.jws workspace. 1. Create a SQL-based view object. The view object selects all of the items in the inventory that have been ordered fewer than five times in total. The query joins the inventory_item, supplier, and line_item tables. a. Open the SqlBasedView project in the Navigator pane. b. Create a new SQL-based view object named UnpopularItems. This is the only view in the project. c. This view object should return those items which have a total ordered quantity of less than 5. You can write the query or use the query below for the new view object. SELECT product_name , product_description , total FROM (SELECT prod.product_name , prod.product_description , sum(nvl(order_items.quantity,0)) as total FROM product_information prod , order_items WHERE prod.product_id = order_items.product_id GROUP BY prod.product_name, prod.product_description HAVING sum(nvl(order_items.quantity,0)) < 5 ORDER BY total) d. Create a new application module for the project and name it SQLBasedViewModule. Include the UnpopularItems view object in the data model. e. Run the Business Components browser and test your SQL-based view. You should see 13 items where five or fewer have been ordered. 2. Create a view object that uses a parameter. The new view object contains inventory items that have less than a specified quantity on hand. The quantity is passed to the query as a run-time parameter. a. Create a new SQL-based ViewObject named InventoryLevelView. The query will join the inventories and product_information tables. It will also sum the quantity_on_hand column from the inventories table since each item can have multiple rows. It should return the product_id, product_name, and a sum of quantity_on_hand values from the inventory_item table. It should return only those rows where the total onhand quantity is less than the parameter value. You could code the query or use the following query.

Oracle9i JDeveloper: Develop Applications with BC4J 13-14

Practice 13-1 (continued) SELECT product_id , product_name , total_on_hand FROM (SELECT prod.product_id , prod.product_name , sum(nvl(inv.quantity_on_hand,0)) as total_on_hand FROM product_information prod , inventories inv WHERE prod.product_id = inv.product_id GROUP BY prod.product_id , prod.product_name HAVING sum(nvl(inv.quantity_on_hand,0)) < 200 ORDER BY total_on_hand) b. Add the view object to the application module and test it with the Business Components Browser. c. Replace the hard-coded value 200 with a parameter placeholder. 3. Create a batch client program to test the parameter based query. a. Create a new Application from the New Gallery. b. Name the application TestClient. Do not include a default frame. c. Add import statements for:
oracle.jbo.client.Configuration; oracle.jbo.*;

d. Replace the code "new TestClient();" with your code to instantiate the SQLBasedView application module. The application name is SQLBasedView.SQLBasedView . The configuration name is SQLBasedViewModuleLocal. e. Add a print statement at the end of the main() to display a success message when you successfully make it through the program. f. Save your changes,compile, and test your program. At this stage, your program does not pull any data from the database, but it should compile and run without error, and display your success message. This proves that you were able to instantiate the application module. With that complete, you can begin to add code that will display data from the Business Components in the SQLBasedView application module. g. Create a string object named howManyStr to hold the value of the commandline argument. h. Add code to make sure an argument is passed. If the program does not receive an argument, display an appropriate error message and quit the application. If there is an argument, set howManyStr to the value and display the value.
Oracle9i JDeveloper: Develop Applications with BC4J 13-15

Practice 13-1 (continued) i. Add code to instantiate the InventoryLevelView object and set its Where clause parameter to the value of the argument from the command line and execute the query on the view object. j. Add a loop to display all of the rows of the view object displaying the product_id, product_name, and total_on_hand k. Modify the project properties to pass a command line argument to your program by editing project properties and selecting the Development ->Runner node. Enter a number in the program argument field. l. Build, save, and test your program.

Oracle9i JDeveloper: Develop Applications with BC4J 13-16

Creating JSP Clients for a Business Components Application

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 60 minutes 45 minutes 105 minutes

Topic Lecture Practice Total

Objectives
After completing this lesson, you should be able to do the following: Define JavaServer Pages Define and use JavaServer Page elements Describe and use data tags and custom data tags Build a default JSP based on a BC4J application Define and use component tags in a JSP

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson describes the JavaServer Pages technology and how to use it to build Web-based applications.

Oracle9i JDeveloper: Develop Applications with BC4J 14-2

What Is a JSP?
JSP is a server-side Java technology which: Leverages on HTML pages but:
Separates user interface content from dynamic, logic-based content Is used by both novice and advanced Java programmers

Contains HTML text freely mixed with Java code (for advanced programmers) Can use XML tags

Copyright Oracle Corporation, 2002. All rights reserved.

About JavaServer Pages JavaServer Pages are ultimately servlets that are written differently. JavaServer Page technology separates the user interface from dynamic content generation, so that designers can easily change the overall page layout without altering the dynamic content. JSP technology supports a reusable component-based design, making it easier and faster than ever to build Web-based applications. Key features of the JavaServer Page technology include: Simplified page generation: HTML-like tags and scriptlets written in the Java programming language encapsulate the logic that generates the content for the page. By separating the presentation design from the application logic that generates the data, JSP-enabled pages make it easier for organizations to reuse and share application logic through custom tags and JavaBeans-based components. This also separates the job responsibilities of the Web designer and Java programmer: Custom tags and beans can be developed by the Java programmer and implemented by the Web designer. Integration with the Java platform: JSP technology is a key component of the Java platform. The Java programming language is the native scripting language for JSP technology pages, and the pages themselves are compiled into Java Servlets. Using JSP technology, organizations can leverage existing Java platform expertise and create highly scalable enterprise applications. Platform and server independence: The JSP specification represents a broad spectrum of industry input and works with a wide variety of Web and application servers.
Oracle9i JDeveloper: Develop Applications with BC4J 14-3

Invoking JavaServer Pages


You can invoke a JSP directly:
http://localhost:8988/<contextroot>/main.jsp

You can invoke a JSP indirectly from:


Another JSP A servlet A plain HTML page

Copyright Oracle Corporation, 2002. All rights reserved.

Invoking JavaServer Pages A JavaServer Page can be invoked by typing the url in the browsers address line or by including an href link or action tag from a servlet or html page. Additionally, a JSP can be invoked from another JSP using links, action tags, or by using JSP directives and scriptlets.

Oracle9i JDeveloper: Develop Applications with BC4J 14-4

Basic JSP Elements


Regular HTML elements Java code expressions that evaluate as string values Scriptlets containing short Java code Declarations which enable you declare variables Directives which enable you to declare global values Custom tags for creating unique functionality useBean for invoking JavaBeans

Copyright Oracle Corporation, 2002. All rights reserved.

JSP Elements This slide lists tags that you can use in a JSP page. These are explained in greater detail in the following pages. Expressions contain Java code, and the code is evaluated to Java strings. Scriptlets contain Java code and are called by the servlets _jspService method. Declarations enable you to declare Java variables. Directives enable you to declare global values. Custom Tags are a mechanism for creating portable libraries for custom functionality JavaBeans are incorporated easily into JavaServer Pages using the useBean tag.

Oracle9i JDeveloper: Develop Applications with BC4J 14-5

Automated JSP Features


A JSP can contain extensible components: Tags (coupled with Business Components for Java (BC4J), or custom-developed) JavaBeans (beans are reused and properties are automatically introspected)

Copyright Oracle Corporation, 2002. All rights reserved.

Automated JSP features When you run a JSP, a Java program and then a Java servlet are generated automatically. Therefore, the first time a JSP is invoked, your response time is likely to be slow. With subsequent requests, however, you get the full benefits of the servlet technology. The JSP engine also uses the Java introspection mechanism to discover all JavaBeans properties referred to in your page. Values are initialized properly in the generated HTML page. In addition, if a bean has already been instantiated by a prior request, it can be reused.

Oracle9i JDeveloper: Develop Applications with BC4J 14-6

Example: The Date JSP Page

Copyright Oracle Corporation, 2002. All rights reserved.

JSP Example The example in this slide was generated without writing a single line of Java code, yet it produces dynamic content. To see how this is possible, you should understand the difference between component-centric and page-centric Web development. Not too long ago, everyone put their business, data, and presentation logic into scripted Web pages. This page-centric model was easy to learn and allowed for fairly rapid development. However, over time people realized that this wasn't the way to build large, scalable Web applications. The logic written for the scripted environments was locked inside pages and was reusable only through cutting and pasting. Presentation logic was regularly mixed with business and data logic, making application maintenance difficult as programmers attempted to modify the look and feel of an application without breaking the tightly coupled business logic. As Web application complexity increased, the limitations of the page-centric model became obvious. At the same time that people were looking for better ways to build Web applications, components were being actively developed in the client-server world. JavaBeans and ActiveX were being used by Java and Windows application developers, respectively.

Oracle9i JDeveloper: Develop Applications with BC4J 14-7

JSP Example (continued) JSP is primarily a component-centric platform. Because of the component-centric nature of JSP, that is, the same components can be shared across JSP pages, it can be used by non Java developers and Java developers alike. NonJava developers can use the JSP tags to work with tags and beans that experienced Java developers created. Java developers can not only make and use tags and beans, but also use Java in JSP pages for finer-grained control over presentation logic that is based on underlying code.

Oracle9i JDeveloper: Develop Applications with BC4J 14-8

Example: The Date JSP Page

<%@ page contentType="text/html;charset=WINDOWS-1252"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=WINDOWS-1252"> <title> Hello World </title> </head> <body> <h2> The current time is: </h2> <p> <% out.println((new java.util.Date()).toString()); %> </p> </body> </html>

Copyright Oracle Corporation, 2002. All rights reserved.

JSP Example (continued) This slide shows how JSP and HTML are used together to create a simple JSP page.

Oracle9i JDeveloper: Develop Applications with BC4J 14-9

Scriptlets
Begin with the sequence <% Contain Java code that is executed every time a request is made End with the sequence %>

<% if(request.getParameter("firstName")==null){ %> Hello World <% } else { %> Hello, <%= request.getParameter("firstName") %> <% } %>

Copyright Oracle Corporation, 2002. All rights reserved.

Scriptlets You may prefer to write simple Java code to generate content. The example in the slide shows how Java code (called a scriptlet) is placed along with normal HTML text and JSP expressions. Notice the way the Java code is completed. The generated Java servlet code contains something similar to the following:
if (request.getParameter("firstName") == null) { out.println("Hello World"); } else { out.println ("Hello,"); out.println (request.getParameter("firstName")); }

Instructor Note At this point you should run the Scriptlet.jsp demonstration. This is the default JSP built by the JSP wizard. Point out that again, Java and HTML are freely mixed and the scriptlet is executed at run time. Next, run the ScriptletandExpr.jsp demo. Run the JSP, and then with the JSP in your browser, append ?firstName=John to the URL. Point out that the JSP again produces dynamic HTML, but unlike the previous demonstration, the generated HTML is related to what an end user might provide as input.
Oracle9i JDeveloper: Develop Applications with BC4J 14-10

Expressions
Begin with the sequence <%= Contain short Java expressions or code, which is interpreted at run time End with the sequence %> Do not end with a semicolon Tremendously increase the power of JavaServer Pages
<%= this.getServletInfo() %> <%= "a" + "b" %>

Copyright Oracle Corporation, 2002. All rights reserved.

Expressions In the example in the slide, the getServletInfo() method is placed in an expression which dynamically invokes the method and places the output in line in the HTML file. What does the last line in the slide do? Instructor Note Answer: The string "ab" appears in the generated HTML document. At this point you should run the Expression.jsp demonstration. Point out that you are generating dynamic HTML, and that HTML and the expressions are freely mixed within the JSP. You may also want to show the generated servlet code for the JSP.

Oracle9i JDeveloper: Develop Applications with BC4J 14-11

Declarations
Begin with the sequence <%! Contain Java declarations End with the sequence ;%> Work well with expressions and scriptlets

<%! private int hitCount = 0; %> This page has been visited <%= ++hitCount %> times.

Copyright Oracle Corporation, 2002. All rights reserved.

Declarations Declarations go together with expressions and scriptlets. In the example in the slide, hitCount is declared for use with an expression. Instructor Note At this point you should run the Declaration.jsp demonstration. Run the JSP as usual and point out the increasing hitCount variable. Optionally, append ?count=77 to the url to point out that the JSP once again produces dynamic HTML, but now it uses the parameter value for hitCount.

Oracle9i JDeveloper: Develop Applications with BC4J 14-12

Directives
Enable you to declare global values Begin with the sequence <%@ End with the sequence %> Are of the following types:
page directive include directive taglib
<%@ page language="java" %> <%@ include file="signature.html" %>

Copyright Oracle Corporation, 2002. All rights reserved.

Directives There are three types of directives: The page directive enables you to declare global values. The example in the slide declares that the language in the JSP is Java. The page directive is covered in further detail on the next slide. The include directive is a handy way of recursively including other JSP pages. The complete syntax of the include directive is given later. The taglib directive is used to specify custom markup tags, discussed later. To use directives in XML, use <jsp:directive.directiveType attribute=value/>. For example, the XML equivalent of <%@ page import=java.io.* %> is <jsp.directive.page import=java.io.* />. Instructor Note At this point you should run the Directive.jsp demonstration. Point out that the contents of the default.jsp are included in the output of Directive.jsp

Oracle9i JDeveloper: Develop Applications with BC4J 14-13

Custom Tags
JSP 1.1 and later allows for the definition of custom JSP tags Tags are used in a JSP to reduce or limit the amount of Java scriptlets in the page Tags are useful for defining custom actions such as:
Accessing a database Defining recurring tasks Sending e-mail

BC4J uses the custom tag technology to generate JSP applications based on business components

Copyright Oracle Corporation, 2002. All rights reserved.

Custom Tags Custom tags are a feature of JSP 1.1 and later. They enable you to create your own tags for use in JSP applications. Tags provide encapsulation of complex behaviors much like Java Beans, but they can also manipulate JSP content. This is useful as JSP pages can often have a large amount of scriptlet code to maintain, and can eventually lose their reusability. Custom tags are useful because they have simpler syntax than scriptlets and are reusable. Therefore, they can be developed by Java programmers and utilized in JSP pages by Web application developers. Custom tags are used in an XML syntax. Similar to HTML tags, there are custom tags without a body: <tagName attribute1=value1 attribute2=value2 /> And tags which have matching end tags, and therefore include a body: <tagName attribute1=value1 attribute2=value2 > tag body </tagName> Note that both types of tags may have attributes to customize the behavior of a tag.

Oracle9i JDeveloper: Develop Applications with BC4J 14-14

The BC4J-Based JSP Application


BC4J-based JSP applications use an implementation of the custom tag technology called data tags and component tags. Use data tags component tags to create forms. Use the JSP Application Wizard to create your application. You can then mix and match forms that are created by the wizard with your own HTML forms, servlets, and JSP pages.

Copyright Oracle Corporation, 2002. All rights reserved.

About JSP Applications A BC4J JSP application allows you to leverage the BC4J components in your application with JSP pages automatically generated by the JSP Application Wizard. Forms for browsing, inserting, and querying records are created for you. This is useful when you want to view a single table, or view two tables in a master-detail relationship. Note: Data tags and component tags are covered later in this lesson.

Oracle9i JDeveloper: Develop Applications with BC4J 14-15

Example

Copyright Oracle Corporation, 2002. All rights reserved.

BC4J Based JSP Application Example The above example shows the forms created for you when developing a BC4J-based JSP application using the wizards.

Oracle9i JDeveloper: Develop Applications with BC4J 14-16

JDeveloper Support for BC4J


JDeveloper supports BC4J application development in various ways:
Wizards BC4J Pages Business logic BC4J data tags Custom tags Presentation logic Component data tags J2EE deployment

Copyright Oracle Corporation, 2002. All rights reserved.

JDeveloper Support for BC4J Applications Several wizards are provided in JDeveloper for creating JSP pages based on BC4J applications. The wizards use an implementation of custom tags to generate JSP applications which contain business components. These tags are called data tags and component tags.

Oracle9i JDeveloper: Develop Applications with BC4J 14-17

Creating BC4J-based Applications


To create a BC4J-based application, perform the following steps: 1. Create Business Components 2. Create a BC4J-Based JSP using the wizard 3. Customize the generated JSP pages using:
BC4J data tags BC4J component tags

Copyright Oracle Corporation, 2002. All rights reserved.

Creating BC4J-based Applications The first step in creating a BC4J Application is to create the BC4J components themselves. This links your JSP application to your database tables using Entity Objects, View Objects, and Associations. The second step in creating a BC4J application is usually to create a JSP application using the wizards. This provides a good starting point, after which BC4J data tags and component tags can be used to customize the application.

Oracle9i JDeveloper: Develop Applications with BC4J 14-18

Invoking the JSP Application Wizard


After the BC4J Components are created, the JSP application can be created:

Copyright Oracle Corporation, 2002. All rights reserved.

Creating a JSP Application 1. Select File > New from the menu bar. 2. Select Business Components JSP Application from the BC4J category to start the wizard. 3. Click the OK button.

Oracle9i JDeveloper: Develop Applications with BC4J 14-19

Set the JSP Application Details

Copyright Oracle Corporation, 2002. All rights reserved.

Define the JSP Details Fill in the Web application details or accept the defaults.

Oracle9i JDeveloper: Develop Applications with BC4J 14-20

Select the BC4J Application Module

Copyright Oracle Corporation, 2002. All rights reserved.

Select the BC4J Application Module Specify the application module that you want to reference in your JSP application.

Oracle9i JDeveloper: Develop Applications with BC4J 14-21

Select Form Types

Copyright Oracle Corporation, 2002. All rights reserved.

Select Form Types Select the view objects you want to create forms for. Then, select the types of forms you want to create. Forms can be created for querying, browsing records, and/or editing records. The Edit form contains links for deleting selected records and inserting new records.

Oracle9i JDeveloper: Develop Applications with BC4J 14-22

Generated Files
A set of JSP files are created for every specified BC4J view The Java source contains BC4J data tags and component tags, which you can use to customize the content of the JSP application. Links are created to allow for master-detail navigation.

Copyright Oracle Corporation, 2002. All rights reserved.

Generated Files An example of a wizard-generated Browse JSP is listed below. The next few slides describe the tags used and their purpose. <%@ taglib uri="/webapp/DataTags.tld" prefix="jbo" %> <html><body> <jbo:ApplicationModule id="am" configname="lesson10comps.Lesson10compsModule.Lesson10compsMo duleLocal" releasemode="Stateful" /> <jbo:DataSource id="ds" appid="am" viewobject="OrdersView" rangesize="3"/> <jbo:DataHandler appid="am" /> <jbo:DataTransaction appid="am" /> <h3>OrdersView Browse Form</h3> <table border="0"> <tr><td ALIGN="right"><jbo:DataScroller datasource="ds" /></td> </tr>

Oracle9i JDeveloper: Develop Applications with BC4J 14-23

Generated Files (continued) <tr><td><jbo:DataTable datasource="ds" edittarget="OrdersView_Edit.jsp"/></td></tr> </table> <jbo:ReleasePageResources /> </body></html>

Oracle9i JDeveloper: Develop Applications with BC4J 14-24

Completed JSP Application

Copyright Oracle Corporation, 2002. All rights reserved.

Completed JSP Application After selecting Finish in the JSP Application Wzard, the forms you selected are generated as JSP pages, along with HTML files for navigating the application. Run main.html to start the application. The slide shows the contents of main.html.

Oracle9i JDeveloper: Develop Applications with BC4J 14-25

What the End User Sees

Browse/Query Insert/Edit
Copyright Oracle Corporation, 2002. All rights reserved.

What the End User Sees The end user can now view, query, insert, or browse data in the view object, using the navigator bar and links within the JSP application

Oracle9i JDeveloper: Develop Applications with BC4J 14-26

BC4J Data Tags


The following tags are included in JDeveloper:
Connections Data Access ApplicationModule, DataSource, Commit, Rollback RowSetIterate, RenderValue, SetAttribute, Row, ShowValue HTML Form Elements Events Intermedia InputText, InputDate, InputHidden OnEvent, FormEvent, UrlEvent AnchorMedia, EmbedImage, EmbedVideo

Copyright Oracle Corporation, 2002. All rights reserved.

BC4J Data Tags The slide shows some of the commonly used BC4J data tags. These are separated into categories in the component palette for ease of use. The ApplicationModule and DataSource tags bind your JSP application to BC4J Components. Tags for data access include RowSetIterate (iterates through a row set in a view object), RenderValue (displays values associated with a viewobject item), and SetAttribute (sets the value of a view object item). Additionally, HTML form elements are matched to view object items with tags such as InputText, InputDate, InputHidden, InputPassword, etc. Event tags are available for creating custom actions depending on user input (for instance, when the user presses a submit button). Additionally, tags for use with Intermedia types are used for inserting HTML object and image tags to insert multimedia data in a JSP.

Oracle9i JDeveloper: Develop Applications with BC4J 14-27

Manually Creating BC4J Applications


Instead of using the BC4J Wizard, BC4J JSP pages can be created manually and bound to business components by inserting ApplicationModule and DataSource data tags. This binds your JSP to an ApplicationModule and ViewObject.
<%@ taglib uri="/webapp/DataTags.tld" prefix="jbo"%> <jbo:ApplicationModule id=BC4JModule" configname=package1.BC4JModule.BC4JModuleLocal " lock="true" releasemode="Stateful" /> <jbo:DataSource id="dsOrders" appid="BC4JModule" viewobject="OrdersView" />

Copyright Oracle Corporation, 2002. All rights reserved.

Manually Creating BC4J-Based Applications You may not want to create BC4J applications using the wizard alone. Therefore, to create custom JSP pages which utilize business components, you will need to bind your JSP to BC4J components. This is done by inserting ApplicationModule and DataSource tags from the component palette into a JSP. Next, the data source is specified by supplying the View Object for this data source as well as the application module name provided in the previous tag.

Oracle9i JDeveloper: Develop Applications with BC4J 14-28

The releasemode attribute

The ApplicationModule data tag includes a releasemode attribute. This attribute defines how the state of application module instances is preserved. There are three valid values for this attribute: Stateful (default) Stateless Reserved

Copyright Oracle Corporation, 2002. All rights reserved.

The releasemode Attribute The releasemode attribute of the ApplicationModule data tag specifies how state is preserved across ApplicationModule instances. This attribute is set depending on how users will access the JSP application. A Stateless releasemode is best used when the JSP pages work independently, and it is not undesirable if a row is returned differently from one session to the next. This also improves performance as the application module does not need to maintain the state information. Use a releasemode of Stateful if you want to preserve changes in records from one invocation to the next. Failover support is provided, because state information is preserved in the database by the application module. A Reserved releasemode is similar to Stateful, except that failover support is not provided. This is the strictest type of releasemode, because the state is preserved until the session times out. Additional Commit and Rollback tags are provided for use with Stateful or Reserved releasemode options.

Oracle9i JDeveloper: Develop Applications with BC4J 14-29

Manually Creating BC4J Applications


BC4J tags can then be mixed with HTML to edit, create, and update ViewObject attributes.
<%--AppModule and DataSource tags go here--%> <table border=0> <tr><th>Orders</th> <th>Order Status</th></tr> <jbo:RowsetIterate datasource="dsOrders" > <tr><td><jbo:RenderValue datasource="dsOrders" dataitem="OrderId" ></jbo:RenderValue></td> <td><jbo:RenderValue datasource="dsOrders" dataitem="OrderStatus" ></jbo:RenderValue></td> </tr> </jbo:RowsetIterate></table>

Copyright Oracle Corporation, 2002. All rights reserved.

Manually Creating BC4J Applications In this example, the RowSetIterate tag is used to loop through rows in the ViewObject corresponding to the DataSource tag created in the previous slide. The RenderValue tags display the value of the OrderId and OrderStatus attributes. This is wrapped in HTML code to display the data in a table. The output is shown below:

Oracle9i JDeveloper: Develop Applications with BC4J 14-30

Practice 14-1 Overview


This practice covers creating a BC4J-based JSP application using BC4J data tags.

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 14-31

Practice 14-1 Start JDeveloper, and open the Practice14.jws workspace. In this practice, build a JSP application that uses data tags. The JSP application uses the OnlineOrders business components application as its data source. The JSP application will display a list of all Customers 1. Create a new project named JSPClient with a JSP client that uses the CustomersView from the OnlineOrders application module as its data source. a. Create a new empty project named JSPCLient. b. Create a new JSP in the JSPClient project by selecting JSP from the Web Objects category in the New gallery. Name the JSP Customers.jsp. c. Edit the source code of the Customers.jsp. Beneath the closing </p> tag, use the component palette to insert an ApplicationModule data tag to point to the OnlineOrders business components application d. Next, add a Data Source data tag from the component palette based on the CustomersView object. Name the datasource dsCustomers and click Finish to generate the tag. 2. Create a table for displaying the names of Customers. Use an HTML table and the RenderValue and RowSetIterate data tags. a. Create an HTML table using the <table border=1> tag. The end </table> tag will be automatically generated for you. b. Between the beginning and end table tags, insert a RowSetIterate data tag from the component palette. This tag will iterate through the datasource. c. Between the beginning and end RowSetIterate tags, insert a new table row using <tr> d. Between the beginning and end <tr> tags, insert new columns using the <td> tag. e. Insert a RenderValue data tag between the beginning and end <td> tags to display the values of the CustomerId attributes in the dsCustomers data source. f. Insert additional RenderValue tags for the CustFirstName and CustLastName attributes. 3. Test the application by right-clicking on Customers.jsp and selecting Run. The ID, first name, and last name of each customer in the Customers ViewObject should be displayed in an HTML table in the browser.

Oracle9i JDeveloper: Develop Applications with BC4J 14-32

Component Tags
Component tags use a JSP include directive to reference a JSP which serves as a template for rendering ViewObject data. They allow you to change ViewObject presentation without having to modify every JSP in your application.

Copyright Oracle Corporation, 2002. All rights reserved.

Component Tags Component tags are also helpful when developing BC4J applications. They use BC4J data tags to display forms for editing, querying, and browsing data. When utilizing a component tag, a JSP include directive is used to reference a template JSP. The name of this JSP corresponds to the tag used, and is automatically included in your project.

Oracle9i JDeveloper: Develop Applications with BC4J 14-33

Component Tags
Component tags included in Oracle9i JDeveloper:
Component Tag DataTable DataRecord Purpose Displays a table bound to a ViewObject Displays a record in a ViewObject

DataTransaction Renders Commit and Rollback buttons DataScroller DataEdit DataQuery Displays a Previous|Next type scroller Displays a form to edit a record A tag to query a ViewObject

Copyright Oracle Corporation, 2002. All rights reserved.

Component Tags (continued) Component tags serve to further separate business and presentation logic within JavaServer Pages. Several component tags are available from the component palette, including tags to display ViewObject data, and display common elements such as scrollbars and navigation bars. An additional tag, DataHandler, is the only component tag which does not render html. This tag is used in conjunction with other component tags. It retrieves the type of event requested (Create, Delete, NextSet, etc.) and passes necessary parameters to calling component tags. Instructor Note You may wish to show students available component tags from the JDeveloper Component Palette.

Oracle9i JDeveloper: Develop Applications with BC4J 14-34

Using Component Tags


To use component tags, perform the following tasks: 1. Create a JSP in Oracle9i JDeveloper 2. Insert ApplicationModule and DataSource data tags to bind your JSP to an ApplicationModule and ViewObject(s). 3. Insert component tags for performing queries, rendering rows, and updating data. 4. Modify the component tag JSP file as needed. For instance, to change the way your application will render data in tables, modify the cell spacing specified in DataTableComponent.jsp

Copyright Oracle Corporation, 2002. All rights reserved.

Using Component Tags As with BC4J Data Tags, component tags are reliant upon a defined data source. Therefore, the ApplicationModule and DataSource tags should be included in your JSP to bind it to a View Object. Component tags can then be selected from the component palette for displaying forms for editing or displaying attributes in a table. The resulting component tag can be modified if necessary.

Oracle9i JDeveloper: Develop Applications with BC4J 14-35

How Component Tags Work


A snippet of DataTableComponent.jsp:
<% RequestParameters params = HtmlServices.getRequestParameters(pageContext);%> <jbo:DataSourceRef id="dsBrowse" reference='<%=params.getParameter("datasource")%>' /> <table class="clsTable" cellspacing="1" cellpadding="3"> <tr class="clsTableRow"> <jbo:RowsetIterate datasource="dsBrowse" changecurrentrow="false" userange="true"> <td title="<jbo:ShowHint hintname='TOOLTIP'/>" class="tablecell"> <jbo:RenderValue datasource="dsBrowse">##Cell</jbo:RenderValue></td> </tr> </jbo:RowsetIterate> </table>

Copyright Oracle Corporation, 2002. All rights reserved.

How Component Tags Work The above example shows how the DataTableComponent.jsp retrieves the data source from the requesting JSP via pageContext, and uses it to create an HTML table displaying row header and column data from a View Object. This component could be modified to change the attributes displayed or the way they are displayed.

Oracle9i JDeveloper: Develop Applications with BC4J 14-36

Component Tag JSP


The use of component tags makes formatting view object data easier:
<%@ taglib uri="/webapp/DataTags.tld" prefix="jbo" %> <jbo:ApplicationModule id="BC4JModule" configname="package1.BC4JModule.BC4JModuleLocal" username="oe" password="oe" lock="true" releasemode="Stateful" /> <jbo:DataSource id="dsOrders" appid="BC4JModule" viewobject="OrdersView" /> <jbo:DataTable datasource="dsOrders" />

Copyright Oracle Corporation, 2002. All rights reserved.

Component Tag JSP This JSP displays the same data as the slide entitled Manually Creating BC4J Applications. The data source is passed to the DataTableComponent.jsp which iterates through the table definition and rows and displays them in an HTML table. For further customization, component tags can be modified and saved as a different name, for use in select JSP pages. The JSP would then reference the new name in the tag as follows: <jbo:DataTable datasource=dsOrders relativeUrlPath=mycustomDataTableComponent.jsp />

Oracle9i JDeveloper: Develop Applications with BC4J 14-37

Component Tag JSP

Copyright Oracle Corporation, 2002. All rights reserved.

Component Tag JSP (continued) The slide shows the completed JSP which uses component tags to render the OrdersView View Object data in a formatted table, along with a navigational control.

Oracle9i JDeveloper: Develop Applications with BC4J 14-38

Practice 14-2 Overview


This practice covers customizing a wizard generated JSP application using component tags.

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 14-39

Practice 14-2 In this practice, you will create a BC4J-based JSP application using the wizards and customize the generated JSP application to view the data in a master-detail format. 1. First, create a form for browsing and editing the OrdersView object in JSPClient project. a. Create a new data page form using the BC4J JSP wizard by selecting Browse and Edit Form from the BC4J JSP Category in the New Gallery. b. Select the OnlineOrders application and OrdersView as the view object for this form. When you click Finish, the wizard will generate several files for you. OrdersView_BrowseEdit.jsp is the main form for browsing and editing. This file uses three component tags, DataHandler, DataScroller, and DataTable. Additional files are added for editing the OrdersView attributes, and for using Intermedia data types. c. Double-click OrdersView_BrowseEdit.jsp in the navigator to display the code in the code editor. Notice that the ApplicationModule and DataSource data tags are used to link the JSP to a View Object. Additionally, the DataTableComponent.jsp contains RowSetIterate and RenderValue tags for displaying ViewObject attributes. d. Right-click OrdersView_BrowseEdit.jsp and select Run to test the functionality of the form. 2. Next, create a form for browsing the OrderItems ViewObject. a. Create a new form in the JSPClient project by selecting Browse Form from the BC4J JSP Category in the New Gallery. b. Base this form on the OrderItemsView1 ViewObject. This View will be in sync with its master form. The OrderItemsView1 ViewObject is in the OnlineOrders application module. Note that the component JSP pages were added to your project by the wizard in step 1. The OrderItems Browse form and the Orders Browse and Edit form have several of these component tags in common. Therefore, they will be overwritten when the second form is generated. Click Yes to overwrite each of the JSP pages. 3. Finally, link the two forms together so that the details can be retrieved from the master form. To do this, you will modify the master JSP to include a link for viewing that record's detail. You will also modify the detail JSP to display the detail records based on the row selected in the master JSP. You will make these modifications in the DataTableComponent.jsp and OrderItemsView_Browse.jsp a. First, save the DataTableComponent.jsp as DataTableComponentMaster.jsp. To do this, you must trick the IDE into thinking the file has been modified. Edit the DataTableComponent.jsp. and insert a space anywhere in DataTableComponent.jsp and then delete the space. That will mark the file as changed. You can now select Save As from the file menu and save the file as DataTableComponentMaster.jsp. b. Modify OrdersView_BrowseEdit.jsp to use the new component tag by adding the following attribute to the jbo:DataTable tag: relativeUrlPath="DataTableComponentMaster.jsp"
Oracle9i JDeveloper: Develop Applications with BC4J 14-40

Practice 14-2 (continued) c. Next, add a link for viewing details in the master component tag. d. Locate the href link tags in DataTableComponentMaster.jsp for deleting and editing records. These are similar to the link you will be creating to OrderItemsView1_Browse.jsp. e. Add the following code between the end </td> and the opening scriptlet (<%) of the UrlEvent named Edit.
<td> <a href="<jbo:UrlEvent targeturl='OrderItemsView1_Browse.jsp' event='details' addrowkey='true' />">View Detail</a> </td>

f. This adds a link to the end of the row and passes the row key for the current row to the OrderItemsView1_Browse.jsp. 4. Next, create the URLEvent details, that is called from the href link. a. Open the OrderItemsView1_Browse.jsp in the editor. b. Add the following code after the <jbo:DataHandler appid="am" /> tag:
<jbo:OnEvent name="details"> <jbo:DataSource id="dsOrders" appid="am" viewobject="OrdersView" /> <jbo:Row id="myrow" datasource="dsOrders" rowkeyparam="jboRowKey" action="Find" /> </jbo:OnEvent> Note: This creates a new event named details which finds the current row for the selected master record, using the datasource and rowkeyparam attributes

c. Build JSPClient.jpr and run OrdersView_BrowseEdit.jsp to test the new functionality.

Oracle9i JDeveloper: Develop Applications with BC4J 14-41

Creating a JClient Application for a Business Components Application

Copyright Oracle Corporation, 2002. All rights reserved.

ILT Schedule:

Timing 45 minutes 45 minutes 90 minutes

Topic Lecture Practice Total

Objectives
After completing this module, you should be able to do the following: Describe JClient Architecture Describe how JClient is related to BC4J Describe how JClient operates Create a simple Form using JClient wizards

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 15-2

Overview
Create a data model Create a simple form Add enhancements

View

Controller

BC4J

Model

Copyright Oracle Corporation, 2002. All rights reserved.

Overview Create a Data Model Before you can create a form, you must have a business component project. You can specify an empty project for your business components, or you can use business components which were created in another project. The JFC/Swing components are based on the Model-ViewController (MVC) architecture. JDeveloper supplies specialized version of these models that know how to communicate with business components. MVC is discussed later in the module. Create a Simple Form JDevelopers JClient form wizard saves you time by allowing you to quickly design and implement forms. Add Enhancements After building on JClient forms using the wizard, you can invoke the code editor and add code to enhance your application. Because of JDevelopers synchronization feature, the visual effects of adding code may also be seen in the UI editor and the property inspector.

Oracle9i JDeveloper: Develop Applications with BC4J 15-3

What Is JClient?
JClient is a framework that enables users to build Java UI applications. It enables Java UI objects to interact with BC4J. Functionally it is divided into design time (DT) components and run-time (RT) components.
At DT, the user can select JClient wizards to generate a JClient application. At RT, the JClient configuration file is read at startup by the first frame or applet class.

Copyright Oracle Corporation, 2002. All rights reserved.

What Is JClient? JClient is a framework, consisting of a set of Java classes that enable you to quickly and efficiently build Java UI applications (JUI), which are consistent in appearance and behavior. Functionally, the JClient environment is divided into design time (DT) and run-time (RT) components. Because the DT components are fully integrated with JDevelopers IDE, you can select JClient wizards to generate a JClient application quickly. Hooks into the JClient RT components are generated by the IDE and DT components. You can use JClient DT components, without a full command of the JClient RT APIs. This allows you to quickly build, run, and test a JClient application.

Oracle9i JDeveloper: Develop Applications with BC4J 15-4

What Are the Components of JClient?


Development Time (DT) packages Meta-object manager (MOM) package Binding package JUI packages

Copyright Oracle Corporation, 2002. All rights reserved.

What Are the Components of JClient? DT packages are integrated with the JDeveloper IDE. They are further divided into DT wizards, JClient specific property editor extensions, and code generation packages. The Meta-object manager (MOM) package contains classes that manage JClient metaobjects. Specifically, JUMetaObjectManager manages application meta-objects and act as the factory for the JClient application (JUApplication) object. The Binding package provides a base mechanism for binding UI objects to BC4J. When BC4J generates events, for example, rangeRefreshed, navigated and so on, the Binding package provides the infrastructure by which these events are processed in the context of UI objects. It also provides a set of methods which turn a user action on a UI object into BC4J API calls. The Binding package is intentionally built to be generic. It does not have any Swing dependency or assumption. As such, classes in this package may be extended to handle UI objects of different flavors. JUI packages extend the binding package and add Swing specific interactions. Swing events are listened to and appropriately handled.

Oracle9i JDeveloper: Develop Applications with BC4J 15-5

JClient Architecture
For virtually every type of UI component model identified in SDK version 1.3, JDeveloper supplies a specialized version of that model which knows how to communicate with BC4J.
View Controller BC4J

Model

Copyright Oracle Corporation, 2002. All rights reserved.

JClient Architecture Model-View-Controller Architecture With MVC there is a logical separation between the model, view, and controller of each UI component. The Model represents the data or state of the component. The View represents the visual aspect of the component, for example the look and feel. The Controller controls the interaction between the Model and the View. For example a JCheckBox is a Swing component which has a defined Model, View, and Controller. When the user interacts with the controller by clicking it, the controller notifies the model that it should change its state (from false to true or vice versa in the case of a default JCheckBox). The view, which is listening for changes in the state of the model, can then update itself, for example, by making the check box appear selected. An important aspect about this architecture is that the model is not aware of the view or views displaying it, nor the controller(s) being used to update it. This independence yields the flexibility of MVC.

Oracle9i JDeveloper: Develop Applications with BC4J 15-6

How Is JClient Related to BC4J?

BC4J
Application Module View Object1 Attribute1 Attribute2 View Object2 Attribute1 . . . Attributen

JClient configuration file(s)

Copyright Oracle Corporation, 2002. All rights reserved.

JClient Details The UI components in the JClient application bind directly to datasources in the Business Components. For example, in the slide, the text field (JTextField) for the First name and Last name is used to allow the user to view and modify an attributes value, and the table (JTable) is used to view and modify all of the attributes in the corresponding View object. The JClient configuration file provides a context for BC4J including where Business Components are deployed and how to connect to them. The Business Components for Java framework manages all of the direct interaction with the database and provides such services as object-relational mapping. The configuration is accessible to all of the classes that are part of the JClient project. What this means is that for a given application or applet, the developer only needs to select the application module(s) once, and reuse the definition throughout the entire project. This information is set at design time when you create a JClient Data Model. The JClient Data Model is responsible for including the appropriate libraries.

Oracle9i JDeveloper: Develop Applications with BC4J 15-7

JClient Model
JClient Models are customized models which are based on the JFC/Swing default models.

JClient UI

JClient Model

BC4J

Copyright Oracle Corporation, 2002. All rights reserved.

JClient Model JClient architecture consists of customized models which are based on the JFC/Swing default models. These models define the interaction between the client and BC4J. Thus, without writing any code, you can build a Java client using standard JFC/Swing components which get and set values in BC4J.

Oracle9i JDeveloper: Develop Applications with BC4J 15-8

JClient Operational Overview


Application bootstrap Frame initialization Layout panel initialization Data browsing panel initialization Populating controls with data Updating data through controls

JClient configuration file(s)

Copyright Oracle Corporation, 2002. All rights reserved.

JClient Operational Overview You run your application by selecting the application bootstrap (the class which has the main()). In our case this is FrameCustomersViewOrdersView1. The following code is executed: Application Bootstrap: JUApplication instantiated Frame Initialization: Instance of FrameCustomersViewOrdersView1 created Layout Panel Initialization: Layout panel created Data Browsing Panel Initialization: Receives its panel binding from the layout panel Populating Controls with Data: The panel UI is updated with data Updating Data through Controls: Data is updated through BC4J APIs.

Oracle9i JDeveloper: Develop Applications with BC4J 15-9

A Simple JClient Form

Copyright Oracle Corporation, 2002. All rights reserved.

A Simple JClient Form This slide shows a simple form created using the JClient form wizard.

Oracle9i JDeveloper: Develop Applications with BC4J 15-10

Creating a Simple JClient Form


Step 1: Create a new workspace. Step 2: Create or add a business. component project Step 3: Create a new empty project. Step 4: Create a JClient data model and add it to the empty project.

Copyright Oracle Corporation, 2002. All rights reserved.

Create a Simple JClient Form Step 1: Create a new workspace Step 2: Create a business component project. Step 3: Create a new empty project for the client data model and form Step 4: Create a JClient Data Model. In the Navigator select the newly created project. Select File > New from the menu. Select JClient Objects from the Categories list and JClient Data Model from the Items list and click OK. Fill in the requested information and click Finish when done.

Oracle9i JDeveloper: Develop Applications with BC4J 15-11

Creating a Simple JClient Form


Step 5: Create a JClient form and add it to the project containing the JClient data model Step 6: Compile and run your application from the toplevel frame

Copyright Oracle Corporation, 2002. All rights reserved.

Create a Simple JClient Form (continued) Step 5: Create a JClient Form and add it to the same project as the JClient Data Model Step 6: Compile and run your application from the top-level frame Create a JClient Form a. In the Navigator select the newly created project. b. Select File > New from the menu. c. Select JClient Objects from the Categories list and JClient Form from the Items list and click OK. e. Select the type of form you want to create and enter the requested information. f. Click Finish when done. Compile and Run Your Application a. Right-click the BC4J project in the navigator. b. Select Make from the menu. c. Right-click FrameOrdersViewOrderItemsView1.java (top-level frame) in the navigator. d. Select Run from the menu.

Oracle9i JDeveloper: Develop Applications with BC4J 15-12

What Files Has JDeveloper Generated?


Project2.cpx is the client project definition file. FrameCustomersViewOrdersView1.java is the application bootstrap. LYPanelCustomersViewOrdersView1.java is the layout panel definition. PanelCustomersView.java and PanelOrdersView1.java are panels which contain the data entry fields.

Copyright Oracle Corporation, 2002. All rights reserved.

What Files Has JDeveloper Generated? Project2.cpx: The project definition file FrameCustomersViewOrdersView1.java: The application bootstrap file, called to run the application LYPanelCustomersViewOrdersView1.java : The layout panel definition for the page PanelCustomersView.java: The panel for the Customers portion of the page PanelOrdersView1.java: The panel for the Orders portion of the page

Oracle9i JDeveloper: Develop Applications with BC4J 15-13

Client Project File


Under the Session element: Name identifies the name of the JClient data model. Package identifies the BC4J package where the BC4J configurations will be found. Configuration identifies the configuration to run.
<Session Name="ClientDataModel1" Package="mypackage" Configuration="MypackageModuleLocal" > </Session> </JboProject>

Copyright Oracle Corporation, 2002. All rights reserved.

Client Project File Project2.cpx is the project definition file. It contains information about which BC4J package to run with and which configuration to use to connect to the BC4J application.

Oracle9i JDeveloper: Develop Applications with BC4J 15-14

Summary
In this module, you should have learned how to: Describe JClient Architecture Describe how JClient is related to BC4J Describe how JClient operates Create a simple form using JClient wizards

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 15-15

Practice 15-1 Overview


This practice covers the following topics: Creating a JClient data model Creating a JClient form Deploying the application as a simple .jar file Testing the deployed application

Copyright Oracle Corporation, 2002. All rights reserved.

Practice 15-1 Overview In this practice, you will create a JClient Form using the JClient Form Wizard and the Order Entry (OE) schema.

Oracle9i JDeveloper: Develop Applications with BC4J 15-16

Practice Overview
This practice covers the creation of a JClient Form

Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 15-17

Practice 15-1 Start JDeveloper, and open the practice15.jws workspace. In this practice, you will create a BC4J-based JClient application using the wizards. The application is a master-detail form. You will also deploy the application as a stand-alone Java application. 1. Create a JClient Data Model a. In the Navigator select the JClient project. b. Open the New Gallery. c. Select JClient Objects > JClient Data Model. d. Accept the default business component project, and application which should be OnlineOrders.OnlineOrdersModule. e. Accept the default client data model name. f. Click Finish when done. 2. Create a JClient Form. Now that you have a JClient Data Model, you can create a JClient form that uses the Data Model. a. Open the New Gallery in the JClient project b. Select JClient Objects > JClient Form to invoke the JClient Form wizard. c. Select Master-Detail Tables as the type of form and Frame as the implementation style. d. Select Master and Detail templates. You may accept the default values or choose whichever you think will look and behave the best. e. Accept the OnlineOrdersModule as the Data Model for this form. f. Select the CustomersView as the Master object and OrdersView1 as the detail object. g. Select the following attributes for the CustomersView: CustomersId CustFirstName CustLastName CustAddress CreditLimit Status h. Select the following attributes for the OrdersView: OrderId OrderDate OrderMode OrderStatus OrderTotal i. Change the package name to JClient. j. Click Finish when done. k. Build, save, and test your project. To test your application , right-click FrameCustomersViewOrdersView1.java and select run from the shortcut menu.

Oracle9i JDeveloper: Develop Applications with BC4J 15-18

Practice 15-1 (continued) 3. Create a deployment profile for your application. a. Create a new Deployment Profile from the New Gallery, select JAR file Simple Archive. Accept the default name or choose a different name. b. In the Files node, select the files you want to include in the archive. For our purposes, select all the files. c. In the JAR options, make sure Include Manifest File is selected. Be sure the enter the fully qualified location of the Main Class. For example: JClient.FrameCustomersViewOrdersView1 d. In the Dependency Analyzer node, select the libraries you want to repackage into your .jar file. Include the following libraries:
Business Component Libraries (your workspace classes) JClient Runtime bc4jui.jar JDeveloper Runtime all libraries BC4J Runtime all libraries Oracle JDBC all libraries Connection Manager all libraries BC4J Oracle Domains all libraries

e. Click OK to finish creating the deployment profile. 4. Deploy the application. a. Right-click the deployment profile you just created and select Deploy to from the shortcut menu. b. Accept the default location for your deployment which is the same as your project directory. Enter a name for the .jar file. You could use the project name for example. c. You have now deployed your JClient application. 5. Test your deployed application. a. Open a command window be clicking on the Windows Start button and selecting Run. Enter cmd in the Open field and click OK. b. In the command window, change to the directory that holds the JDK. That directory is <JDevHome>\jdk\bin. To change directories in a command window, type CD followed by the directory name. c. Once you are in the correct directory start your application by running Java with an argument that points to your deployed application. The command is:
java -jar <JDevHome>\jdev\mywork\Practice15\JClient\<MyJar>.jar

(Where <JDevHome> is the name of the directory in which JDeveloper is installed, and <MyJar> is the name you chose for the application deployment .jar file).

Oracle9i JDeveloper: Develop Applications with BC4J 15-19

Business Component Applications Best Practices

Copyright Oracle Corporation, 2002. All rights reserved.

Schedule:

Timing 30 minutes 30 minutes

Topic Lecture Total

Objectives
After completing this lesson, you should be able to describe the best practices for developing Business Components for Java applications.

Copyright Oracle Corporation, 2002. All rights reserved.

Lesson Aim This lesson describes the best practices for building BC4J applications.

Oracle9i JDeveloper: Develop Applications with BC4J 16-2

Put Business Logic in the Right Place


Put business logic in the middle-tier Put special client-callable methods in
Application modules View objects View rows
Application module Client applications View object View row Business logic (Entity objects)

Copyright Oracle Corporation, 2002. All rights reserved.

Put Business Logic in the Right Place Business Components for Java is designed to be an enterprisewide multitier application development tool. To take advantage of the technology, you should put the business logic in the most effective and efficient layer of the multitier application. The best place for business logic is in the middle-tier Entity objects. These objects manage all interaction with the data source and are deployed to the middle-tier server. If you have methods that you want to expose to client applications, place those in either the application module, the view objects, or the view row object. Where you put the methods depends on what you want the methods to do. The following are some guidelines for deciding where to put the methods: Application Module: Data-intensive calculations that do not depend on a single view object should go into the application module. For example, a calculation of the most ordered items or the total value of orders placed within a month would be good candidates for application module methods. You could also place methods that check or enforce any security restrictions in the application module. View Objects: Methods that need access to data contained in multiple rows should be placed in the view object. These methods could calculate the total of all line items on an order.
Oracle9i JDeveloper: Develop Applications with BC4J 16-3

Put Business Logic in the Right Place (continued) View Row Objects: Methods in a view row object allow a client program to operate on individual rows of data. There are three types of custom view row methods you may want to create: - Accessor Methods: JDeveloper9i generates typesafe accessor methods in the View Row class. You would modify or augment these methods to enhance the default behavior of these get and set methods.You could also add your own methods that return a concatenation of other attributes. For example you could create a getFullName() method that returns a concatenated String containing the FirstName plus the LastName of a Customer. - Delegator Methods: By design, client applications should not have access to methods within an entity object. If you want an entity method to be exposed, create a delegator method in the view row object that executes the entity method. - Entity-Independent Methods: These methods are useful if the calculation derives values from multiple entity objects or no entity objects at all.

Oracle9i JDeveloper: Develop Applications with BC4J 16-4

Use Interfaces
BC4J provides interfaces to the BC4J classes. Maintain tier independence by coding to those interfaces. Create the interface by exporting the client or client row methods.

Copyright Oracle Corporation, 2002. All rights reserved.

Use Interfaces BC4J provides for tier independence by using interfaces to all of the View and View Row classes. These interfaces contain method signatures that correspond to the methods you choose to publish to client applications. You publish or expose these methods from the View or View Row wizards. After you publish the method you want to expose, JDeveloper9i creates an interface class that your clients can access. By accessing this interface, the client deployment can remain thin regardless of the deployment method you choose. If you choose to create a Java application to access your BC4J application module, it only needs to contain the interface class. You will not need to deploy the entire BC4J application to the client. The client will access the interface and the framework will automatically call the appropriate implementation.

Oracle9i JDeveloper: Develop Applications with BC4J 16-5

Deployment Configuration
Use Web module deployment when possible. Deploy the Web module with your client. Choose Web module of EJB deployment. Both are J2EE compliant. BC4J framework allows you to easily switch between the two models.

Copyright Oracle Corporation, 2002. All rights reserved.

Deployment Configuration Your application will have the best performance and scalability if you deploy the application as a Web module with your client. This deployment method is recommended over an EJB deployment model. Unless you have specific deployment criteria such as distributing transactions or special EJB security issues, you should use Web module deployment. Note that both Web module deployment and EJB deployment are both fully J2EE-compliant methods. BC4J allows you to easily switch between the two deployment models so you can test for performance and scalability.

Oracle9i JDeveloper: Develop Applications with BC4J 16-6

Use Application Module Pooling


BC4J provides for pooling application modules. Tune the application pool for your expected client loads. Use stateless mode whenever possible.

Copyright Oracle Corporation, 2002. All rights reserved.

Use Application Module Pooling A client can use application module instances from a pool of instances called an application module pool. The application module pool is managed at runtime by BC4J. It contains a defined number of instances of an application module that clients can check out and return to the pool as needed. By using the pool, the instances are created before they are needed which reduces the amount of time a client waits for an application module. There are several benefits of using a pool: Reduces the amount of time required to obtain server side resources Allows a small number of instances to serve a large number of requests Addresses the requirements of web applications that handle a large number of incoming requests Lets you preserve state when required You should tune the number of pre-instantiated instances to the highest number of concurrent users. If the number is to low, then the pool will need to create new instances often or swap instances between clients. Both of these actions require resources and are less effective than having the right number of instances ready.

Oracle9i JDeveloper: Develop Applications with BC4J 16-7

Use Application Module Pooling (continued) If your client needs to keep track of the application state, you can use Stateful mode. In a Stateful JSP application, the client release the application module back to the pool when it is not needed. The pool keeps the state of the application available by either writing the state to the database and restoring it when the client needs it again, or by giving the same instance back to the client. Both of these options maintain state but do require additional resources. The best method for dealing with an application pool is to release the application module in stateless mode. This is the most efficient and provides the best performance and scalability.

Oracle9i JDeveloper: Develop Applications with BC4J 16-8

SQL-Only Views
Use SQL-only views for query only data. Use forward-only views when possible. Call setForwardOnly() on the view.

Copyright Oracle Corporation, 2002. All rights reserved.

SQL-Only Views Views are objects that interact with client applications. They cache data that is read-only while the entity objects cache data that is selected for update or insert. View objects that use only the view cache are more efficient that those that use both caches. The entity cache is used to enforce business rules when the data is updateable. If the data is read-only, then the view cache is used by itself. To take advantage of this, create SQL-based views for those views that will be used only for reference and not for update. Another way to improve view object performance is to modify the properties of the view object at runtime to make it a forward only view. A forward only view prevents data from entering the view cache. This is useful if the view is going to be used in a forward only direction. For example if you are formatting the view object data for a web page or for a batch operation that proceeds linearly through the data, you would use a forward only view. To set the view to forward only mode, call the setForwardOnly() method on the view object after you instantiate it.

Oracle9i JDeveloper: Develop Applications with BC4J 16-9

Application Module Size


Keep application modules small. They should correspond to a task. Exclude unnecessary views and view links. Consider creating views dynamically.

Copyright Oracle Corporation, 2002. All rights reserved.

Application Module Size A root application module should correspond to one task; anything that you would include in a single database transaction. Do not put more view objects or view links than you will need for a particular task in a single application module. In addition, consider deferring the creation of view links by creating them dynamically with createViewLink(). If you include all view links at design time, the business logic tier will automatically execute queries for all detail view objects when your client navigates through a master view object. Deferring view link creation will prevent the business logic tier from executing queries for detail view objects that you do not yet need. For example, for a form in which detail rows are displayed only on request (rather than automatically), including a view link at design time would force the business logic tier to automatically execute a query that might well be unnecessary. To prevent this, you should create a view link dynamically when the detail rows are requested. By contrast, for a form in which detail rows are displayed as soon as a master is selected, you should use a view link created at design time to avoid the runtime overhead of calling createViewLink().

Oracle9i JDeveloper: Develop Applications with BC4J 16-10

Query Conditions
Use Oracle style parameters when possible.
They are faster in an Oracle environment than the generic JDBC style parameters. Use JDBC style parameters when using a nonOracle driver or if a parameter is used more than once in a where clause.

Implement Query conditions at design time. Use parameterized queries when necessary.

Copyright Oracle Corporation, 2002. All rights reserved.

Query Conditions Oracle-style bind parameters (:1, :2, etc) are more performant than JDBC-style bind parameters. There are two reasons to use JDBC-style bind parameters: If you are using a non-Oracle JDBC driver If you have more than one occurrence of the same parameter in the where clause You should include any portion of your query condition that you know in advance in the WHERE clause field in the View Object wizard. Only use setWhereClause() for genuinely dynamic query conditions. Even if your query conditions are genuinely dynamic, you may be able to use parameterized queries instead of setWhereClause(). For example, if your view object needs to execute a query with the where clause "EMPLOYEE_ID=<x>" for various values of x, use a parameterized where clause such as "EMPLOYEE_ID=:1". This is more efficient than repeatedly calling setWhereClause().

Oracle9i JDeveloper: Develop Applications with BC4J 16-11

Summary
In this lesson, you should have learned how to: Put business logic in the right place Always code to the BC4J interfaces for tier independence Use a Web module deployment model when possible Use application module pooling in the middle tier Use SQL-only views for query only data Use forward-only views when possible Keep application modules small Use Oracle-style parameters
Copyright Oracle Corporation, 2002. All rights reserved.

Oracle9i JDeveloper: Develop Applications with BC4J 16-12

Order Entry Schema

Copyright Oracle Corporation, 2002. All rights reserved.

Order Entry Schema CUSTOMERS CUSTOMER_ID CUST_FIRST_NAME CUST_LAST_NAME CUST_ADDRESS PHONE_NUMBERS NLS_LANGUAGE NLS_TERRITORY CREDIT_LIMIT CUST_EMAIL ACCOUNT_MGR_ID CUST_GEO_LOCATION STATUS NUMBER(6) VARCHAR2(20) VARCHAR2(20) CUST_ADDRESS_TYP PHONE_LIST_TYP VARCHAR2(3) VARCHAR2(30) NUMBER(9,2) VARCHAR2(30) NUMBER(6) MDSYS.SDO_GEOMETRY VARCHAR2(10)

To Product Media Schema

ORDERS PRODUCT_INFORMATION ORDER_ID ORDER_DATE ORDER_MODE CUSTOMER_ID ORDER_STATUS ORDER_TOTAL SALES_REP_ID PROMOTION_ID NUMBER(12) TIMESTAMP(6) VARCHAR2(8) NUMBER(6) NUMBER(2) NUMBER(8,2) NUMBER(6) NUMBER(6) PRODUCT_ID PRODUCT_NAME PRODUCT_DESCRIPTION CATEGORY_ID WEIGHT_CLASS WARRANTY_PERIOD SUPPLIER_ID PRODUCT_STATUS LIST_PRICE MIN_PRICE CATALOG_URL NUMBER(6) VARCHAR2(50) VARCHAR2(2000) NUMBER(2) NUMBER(1) INTERVAL NUMBER(6) VARCHAR2(20) NUMBER(8,2) NUMBER(8,2) VARCHAR2(50)

ORDER_ITEMS ORDER_ID LINE_ITEM_ID PRODUCT_ID UNIT_PRICE QUANTITY DISCOUNT_UNIT_PRICE NUMBER(12) NUMBER(3) NUMBER(6) NUMBER(8,2) NUMBER(8) NUMBER(8,2)

Oracle9i JDeveloper: Develop Applications with BC4J A-2

Product Media Schema

CATEGORIES_TAB CATEGORY_NAME VARCHAR2(50) CATEGORY_DESCRIPTION VARCHAR2(1000) CATEGORY_ID NUMBER(2)

ONLINE_MEDIA PRODUCT_ID PRODUCT_PHOTO PRODUCT_PHOTO_SIGNATURE PRODUCT_THUMBNAIL PRODUCT_VIDEO PRODUCT_AUDIO PRODUCT_TEXT PRODUCT_TESTIMONIALS NUMBER(6) ORDSYS.ORDIMAGE ORDSYS.ORDIMAGESIGNATURE ORDSYS.ORDIMAGE ORDSYS.ORDVIDEO ORDSYS.ORDAUDIO CLOB ORDSYS.ORDDOC

PRINT_MEDIA PRODUCT_ID AD_ID AD_COMPOSITE AD_SOURCETEXT AD_FINALTEXT AD_FLTEXTN AD_TEXTDOCS_NTAB AD_PHOTO AD_GRAPHIC AD_HEADER PRESS_RELEASE NUMBER(6) NUMBER(6) BLOB CLOB CLOB NCLOB TEXTDOC_TAB BLOB BINARY FILE LOB ADHEADER_TYP LONG

Oracle9i JDeveloper: Develop Applications with BC4J A-3

Oracle9i JDeveloper: Develop Applications with BC4J A-4

Practice Solutions

Copyright Oracle Corporation, 2002. All rights reserved.

Practice 2-1 1. Start JDeveloper9i and open an existing workspace. a. Select File > Open. b. Select the workspace practice02.jws and click Open. The workspace is in the directory <JDeveloper>/jdev/mywork/practice02. 2. Create a new project and application. a. Right click the workspace you just created and select New Project from the context menu. b. From the New Gallery, select Projects -> Application Project. c. In Step 1 of the Project Wizard, change the project directory to Hello and the project name to Hello.jpr. You can double-click Project1 to select it, then type Hello. d. In the next step, enter practice02 as the Default Package Name. Accept the default Java Source Path and Output Directory. e. In the next step, accept the default library JDeveloper Runtime. f. Click Finish. The Project Wizard closes and the Application Wizard opens. g. In the Application Wizard, accept the defaults except for the Frame selection. Select Do not add a default frame and click OK. 3. Add some code to your application. a. In the Navigator pane, double-click Application1.java to edit the source code, if the code editor is not already open. b. In the Application1 constructor, enter some code to perform some operations on a String or StringBuffer, and print out the results. You can use the example below. As you enter the code, you can make use of the JDeveloper9i statement completion functionality: Pause before entering a method name. For example, in the second line of the example, enter sb and then pause. You will see a list of StringBuffer methods, and you can select from this list or continue typing to narrow your selection from the list. Pause before entering a method parameter. For example, type sb.append. (If you pause, you will see a list of parameter types for the different versions of the append function.) Here is an example you can use: StringBuffer sb = new StringBuffer("Welcome"); sb.append(" to the world"); System.out.println(sb); public Application1() { StringBuffer sb = new StringBuffer("Welcome"); sb.append(" to the world!"); System.out.println(sb); String s = "My String object"; System.out.println(s.length()); }
Oracle9i JDeveloper: Develop Applications with BC4J B-2

Practice 2-1 (continued) 4. Compile and run your application. a. Click the Save All button to save your code. b. Click the Make or Build button to compile your application. c. Click the Run button to run your application. 5. Fix compilation errors. a. Add some code to the constructor that contains compilation errors. For example: String s; System.out.println(s.length()) b. Rebuild or make your project, and fix the compilation errors. 6. View the documentation for a class. a. In your source code, right-click the word StringBuffer and select Browse symbol at cursor from the Context menu. The viewer that appears contains the source for the StringBuffer class. If the source was not available in your environment, the viewer would contain generated stubs for the available methods. b. In your source code, right-click StringBuffer again. This time select "Browse JavaDoc". If you have time 7. Create a new applet. a. Right-click the Hello.jpr project and select New from the context menu. b. Select Web Objects -> Applet from the New Gallery. c. Accept the defaults and click "Can Run Standalone". Click OK. 8. Add some visual components to your applet. a. Edit the applets design: b. Right-click Applet1.java in the Navigator pane. Select UI Editor from the context menu. Change the applets layout manager to XYLayout: Select this in the Structure pane. In the property inspector, change the layout property to XYLayout. c. Add a button to the applet. d. Select the Swing from the drop list on the Component palette. Click the Jbutton icon. Hint: The tool tips tell you the name of each icon. Click the applet form in the viewer to add the button; drag the edges of the button if you want to resize it. e. Change the button text to YES by editing its Text property in the property inspector. f. Add a second button and change its text to NO. g. Add a text field to your applet. (Hint: Use the JTextField icon in the Component palette). Make sure that its Text property is blank.) Drag the edges of the text field if you want to resize it.

Oracle9i JDeveloper: Develop Applications with BC4J B-3

Practice 2-1 (continued) 9. Add event handlers to the buttons to make them display text in the text field when a button is clicked. a. Click the Yes button in the viewer. b. Select the Events tab in the Property Inspector. c. Click the space to the right of actionPerformed, and then click the browse () button. This button will create an actionPerformed method in your applet. Accept the default name for the method and click OK. The source code viewer is now displayed, with the new event-handler method highlighted. You can also double-click the button in the design view to create the event-handler method. d. Enter the following line of code on the blank line after the highlighted line: jTextField1.setText("YES!"); e. Go back to the UI Editor and add an event handler to the No button in the same way. Enter the following line of code for the method: jTextField1.setText("NO!");

void jButton1_actionPerformed(ActionEvent e) { jTextField1.setText("Yes"); } void jButton2_actionPerformed(ActionEvent e) { jTextField1.setText("No"); }

10. Run your applet and test your code.

Oracle9i JDeveloper: Develop Applications with BC4J B-4

Practice 3-1 Start JDeveloper9i, and open the workspace practice03.jws. 1. Create a new JDBC connection. a. Expand the Connections node in the JDeveloper Navigator pane. b. Right-click Database and select New Connection from the context menu, which launches the Database Connection Wizard. c. Enter bc4j in the Name field, and select JDBC as the connection type. You can choose any name you wish but the practices and examples all use bc4j as the connection name. d. Enter the username and password information for your database, and select Include password in deployment archive. Leave the Role field blank. e. Select the thin JDBC driver. f. Enter the host ID, SID, and port number that was given to you by your instructor. g. Click the Test Connection button to test the connection. h. Click Finish to save the connection. 2. Create a new project containing business components. a. Start the Project Wizard by selecting File > New from the menu or by selecting New Project from the Workspace context menu (right-click the workspace node). b. Select Projects -> Project with Business Components from the New Gallery. c. In the Project Wizard, change the last part of the directory name to and the project file name to bc4j. To continue, click Next. d. In the next step, change the Default Package name to bc4j. Accept the remaining defaults e. Click Finish, and the Business Components Project Wizard starts. 3. Create a new business components application. a. In Step 1 of the Business Components Project Wizard, select bc4j as the connection, and then click Next. b. In Step 2, verify that the package name is bc4j, and then click Next. c. In Step 3: Select the following tables to create entities: CUSTOMERS INVENTORIES ORDERS ORDER_ITEMS ii. Select View Objects and View Links, and select Application Module. iii. Click Next, then Finish. d. Review the Navigator pane to see what JDeveloper has created, and then save all of your files. i.

Oracle9i JDeveloper: Develop Applications with BC4J B-5

Practice 3-1 (continued) 4. Test your application. a. In the Navigator pane, right-click on your application module (Bc4jModule) and select Test from the Context menu. b. In the dialog box, verify that the middle-tier server type is set to Local and the JDBC connection is set to bc4j, and then click Connect. c. In the browser, double-click CustomersView and browse the customers. d. Double-click OrdersView1 and browse the orders. Notice that you can see only the orders for one customer; when you go back to the CustomersView form and navigate to the next record, you see a different set of orders. This is because the applications data model specifies the views in an application as well as how they are linked to each other. a. Close the two open windows. b. Double-click OrdersView, OrderItemsOrderIdFKLink, and OrderItemsView1. Undock each one to make them independent windows. (Note: A slide earlier in this lesson describes the browser buttons and reminds you how to do this.) c. In the OrdersView form, navigate through the orders. Watch the other forms as you do this. Which one changes? Why? d. Navigate through a few rows in the OrderItemsView1 form. Which form changes? Why?. e. Use the other forms to navigate through the data, and watch how the data affects each form. f. Close the tester. g. In the Navigator pane, right-click the application module and select Edit. Look at the application modules data model and verify that it defines the way the different forms affect each other in the browser.

Oracle9i JDeveloper: Develop Applications with BC4J B-6

Practice 4-1 Start JDeveloper9i and open the workspace Practice04.jws. 1. Create a new project containing business components. a. Start the Project Wizard by selecting File > New from the menu or by selecting New Project from the Workspace context menu (right-click the workspace node). b. Select Projects -> Project with Business Components from the New Gallery. c. In the Project Wizard, change the last part of the directory name to and the project file name to entities. To continue, click Next. d. In the next step, change the default package name to entities. e. Click Finish, and the Business Components Project Wizard starts. 2. Create a new business components application. a. In Step 1 of the Business Components Project Wizard, select bc4j as the connection, and then click Next. b. In Step 2, verify that the package name is entities, and then click Next. c. In Step 3: Select the following tables to create entities: CUSTOMERS INVENTORIES ORDERS ORDER_ITEMS ii. Select View Objects and View Links, and select Application Module. iii. Click Next, then Finish. d. Review the Navigator pane to see what JDeveloper has created, and then save all of your files. 3. Use the database sequence orders_seq to populate the order_id attribute of the Orders entity. a. Edit the Orders entity b. Change the orderId attribute to use the orders_seq for its value. Hint: Refer the the slide "Mapping an Attribute to a Database Sequence" if you need a reminder of how to do this. The ORDERS table has a database trigger that uses the sequence to populate the ORDER_ID column. c. Save your changes, rebuild your application, and then test your application using the Business Components Browser. d. In the Browser, open the OrdersCustomerIdFkLink form. e. Add a new Order to a Customer. You won't need to assign an OrderId because it will now be retrieved from the database sequence. The only required fields are the OrderDate and the CustomerId. If you choose to complete the other fields, use the existing order rows for sample data. f. Commit the transaction and requery the Customers to see that the sequence number was committed to the database. g. Close the Browser. 4. Use the database trigger on the order_items table to populate the LineItemId attribute. a. Follow the same steps you followed for step 3 only against the OrderItems entity. b. Test your changes by adding a line item to any order. Note: ProductId must be valid and unique within an Order.
Oracle9i JDeveloper: Develop Applications with BC4J B-7

i.

Practice 4-2 To start this practice: Start JDeveloper, open the workspace Practice04.jws, and open the project that you created in Practice 4-1. 1. Add a Validation Rule to Validate Customers Status a. Edit the Customers entity and add a validation rule. b. Your new rule is a ListValidator rule that ensures that the Status attribute has one of the following values: Platinum Gold Silver c. Save your changes and run your application module in the Business Component Browser. d. In the browser, open CustomersView. Change the Status attribute to an invalid value (such as Premium) and press [Enter] or [Tab]. This will trigger the validation rule and an Exception dialog box will appear. e. Click the rollback button to undo your change, and change the Status attribute to a valid value. This time your change is accepted. f. Close the Business Component Browser. 2. Change Your Validation Rule to be Case Insensitive You may have noticed that your validation rule rejects values such as silver, which are invalid only because the case is different. a. Change your validation rule so that it accepts any combination of uppercase and lowercase letters. Hints: You need to add some code in CustomersImpl.java. If you cannot remember the exact name of a method you want to call in your code, type the object name followed by the ., and wait for a second; JDeveloper will bring up a list of methods to select from. public void setStatus(String value) { String status = value.substring(0,1).toUpperCase() + value.substring(1).toLowerCase(); setAttributeInternal(STATUS, status); }

b. Save and rebuild your code, and test your changes in the Business Component Browser.

Oracle9i JDeveloper: Develop Applications with BC4J B-8

Practice 4-2 3. Validate Email Attributes Using a Domain Object a. Create a domain object called EmailAddressDomain that verifies that an attribute is a valid email address. Use the slides on domains earlier in this lesson to remind yourself how to do this. If it checks an attribute and finds an invalid email address, your domain should do the following: throw new oracle.jbo.domain.DomainValidationException( "Invalid Email Address"); Note: If you need help with the code, there is a code snippet at the end of the practice. b. Edit the Customers entity and set the type of its Email attribute to EmailAddressDomain. c. Save your changes and test them in the browser. Try changing the email addresses of a Customer to invalid values and to valid values.
protected void validate() { int atpos = mData.indexOf('@'); int dotpos = mData.lastIndexOf('.'); int lastchar = mData.length() - 1; // Check for conditions that indicate an invalid email address if (atpos == -1 || dotpos == -1 || // there is no "@" or "." atpos == 0 || // string begins with "@" mData.lastIndexOf('@') != atpos || // string contains more than // one "@" mData.indexOf(' ') != -1 || // string contains a space mData.indexOf(',') != -1 || // string contains a comma dotpos < atpos || // there is no "." after the // "@" dotpos == atpos + 1 || // "." immediately follows "@" dotpos == lastchar ) // string ends with "." { throw new oracle.jbo.domain.DomainValidationException ("Invalid email address"); } }

Oracle9i JDeveloper: Develop Applications with BC4J B-9

Practice 4-2 4. Set a Discount for Multiple Quantities a. Add code to OrderItemsImpl.java to enforce the following business rule: We offer a $5 discount on quantities of ten or more on all items. (The discount attribute contains values in dollars.) Note that if there are less than 10 items, the discount should be set to zero. Hint: Add code to OrderItemsImpl.setQuantity() that sets the discount. public void setQuantity(Number value) { if (value.intValue() >= 10) { setDiscountUnitPrice(new Number(5)); } else { setDiscountUnitPrice(new Number(0)); } setAttributeInternal(QUANTITY, value); } b. Test your changes in the browser. Open OrderItemsOrderIdFkLink and insert some line items. Enter a quantity of 10 or more, and then tab out of the quantity column and verify that a discount is entered in the discountUnitPrice column. Insert a row with a quantity of less than 10, and verify that no discount is set.

Oracle9i JDeveloper: Develop Applications with BC4J B-10

Practice 5-1 To begin this practice, start JDeveloper9i, open the workspace Practice05.jws. 1. Create a new project containing business components. a. In the Project Wizard, change the last part of the directory name to and the project file name to associations. To continue, click Next. b. In the next step, change the default package name to associations. c. Click Finish, and the Business Components Project Wizard starts. 2. Create a new business components application. a. In Step 1 of the Business Components Project Wizard, select bc4j as the connection, and then click Next. b. In Step 2, verify that the package name is associations, and then click Next. c. In Step 3: i. Select the following tables to create entities: CUSTOMERS INVENTORIES ORDERS ORDER_ITEMS PRODUCT_INFORMATION ii. Select View Objects and View Links, and select Application Module. iii. Click Next, then Finish. 3. In the last practice, you added code to calculate a discount based on the number of items ordered. The discount was a flat $5, which is not very realistic. In this practice, you will add a discount calculation that is based on the price of the item. a. Add a discount calculation that applies a 10% discount on line items where 10 or more items are ordered. If there are more than 30 items ordered, apply a 15% discount. Get the listPrice from the ProductInformation entity. Set the unitPrice attribute to the listPrice and set the discountUnitPrice attribute to the discounted unitPrice. For example if the listPrice is $100 and the customer orders 20, the discountUnitPrice attribute should be 90. If the order 30 the discountUnitPrice should be 85. Hint: Use variables for the discount percentages. b. Build and test your project. 4. In addition to the quantity based discount, you need to apply a special discount based on the status of the customer. a. If a customer is Platinum, apply an additional 5% discount. This discount is in addition to any quantity discount you have already applied. b. If a customer is Gold, apply an additional 3% discount. This discount is in addition to any quantity discount you have already applied. c. Build and test your project.

Oracle9i JDeveloper: Develop Applications with BC4J B-11

Practice 5-1 (continued)


public void setQuantity(Number value) { // for quantities of ten or more, give a 10% discount // for quantites of thirty or more, give a 15% discount float quantityDiscount; float statusDiscount = 0F; float price = getProductInformation().getListPrice().floatValue(); setUnitPrice(new Number (price)); if (value.intValue() >= 10 && value.intValue() < 30) { quantityDiscount = 90F; // multiplier equivalent for 10% } else if (value.intValue() >= 30) { quantityDiscount = 85F; // multiplier equivalent for 15% } else quantityDiscount = 0F; // code to get the customer status (in step 4) String customerStatus = (getOrders().getCustomers().getStatus()); statusDiscount = 0F; if (customerStatus.equalsIgnoreCase("PLATINUM")) { statusDiscount = 5F; } else if (customerStatus.equalsIgnoreCase("GOLD")) { statusDiscount = 3F; } // end of getting customer status and setting statusDiscount // calculate discount ( - statusDiscount is added in step 4) float discountUnitPrice = ((price * (quantityDiscount - statusDiscount)) / 100); if (statusDiscount == 0F && quantityDiscount == 0F) setDiscountUnitPrice(new Number (price)); else setDiscountUnitPrice(new Number (discountUnitPrice)); setAttributeInternal(QUANTITY, value); }

Oracle9i JDeveloper: Develop Applications with BC4J B-12

Practice 6-1 Start JDeveloper9i, and open the workspace practice06.jws . 1. Create a database object from an entity object. a. Select the NewEntity project in the Navigator pane. b. Think of a new entity to add to the online orders business model. One possibility is to add an entity called Accessories that could be used to look up suggested additional purchases for a particular inventory item. For example, if a customer orders a mobile phone, an application could use this entity to list a case, spare battery, and so on that the customer might like to order. c. Create your new entity using the Entity Wizard; do not base your entity on a database table. d. If your entity links to an existing entity in the model, create a foreign key constraint to define the relationship between your new entity and an existing entity. Create an association corresponding to the foreign key constraint. Hint: When creating a foreign key constraint, enter the database name of the referenced primary key in the References field. 2. Create the components needed to use your new entity. a. Create a default view based on your new entity. b. Create an association between your new entity and the source of its foreign key. c. Create database objects based on your new entity. d. Create a link between the new view and the source view for the link. e. Modify the data model of your application module to include the new view object and new link. f. Save your changes, and test your application using the Business Component browser. Insert some data into your new database table. Test the foreign key constraint by inserting into your view object, using both valid and invalid values for the Join column. 3. Synchronize your Business Components with changing database objects. a. Make a change to your database schema that you can synchronize to. Open a SQL Worksheet by right-clicking the bc4j connection and selecting SQL Worksheet. Enter and run the following SQL statement. alter table customers drop column cust_geo_location; b. Run the synchronize utility to see the differences between your project and the current state of the database. c. Synchronize the Customers entity with the customers database object. d. Edit the CustomersView view and remove the CustGeoLocation attribute. e. Build and test your project.

Oracle9i JDeveloper: Develop Applications with BC4J B-13

Practice 7-1 Create the PriorityOrder view object. Look at the previous slide to remind yourself what this view object looks like. To start the practice, you must open workspace practice07.jws and project Views.jpr. 1. Create a new view object PriorityOrderView based on the Customers entity. 2. Select the CustomerId, CustFirstName, CustLastName, and Status attributes in the Customers entity, and click Finish. 3. Edit PriorityOrderView so that it reflects the following definition: Add Orders to the entities list. Add the following attributes to the list of selected attributes. OrderId Orderdate OrderStatus Edit the Where clause so that the query returns only the rows where the status of the customer is 'Platinum'. 4. Add PriorityOrderView to your application modules data model.
Customers.CUSTOMER_ID = Orders.CUSTOMER_ID and Customers.STATUS = 'Platinum'

5. Build, save, and test your application.

Oracle9i JDeveloper: Develop Applications with BC4J B-14

Practice 7-2 Start JDeveloper and open the workspace practice07.jws and the project Views.jpr. 1. Add a calculated attribute to the OrderItemsView view object to display the total cost of each line item. To calculate a line items total, you need multiply the orderItem quantity * the discountUnitPrice. It is also useful to see the inventory items description, so you will also add code to display the item description. a. Add a calculated attribute to the OrderItemsView view object, using the following information: The name of the attribute is LineTotal. The attribute displays the total cost of the line item (use the discountUnitPrice). Use the attribute query expression to calculate the value of LineTotal. b. Edit the OrderItemsView view object and add ProductionInformation.Description to the view objects attribute list. c. Test your changes using the Business Component Browser. 2. Modify OrderItemsView to recalculate LineTotal when the line item changes. In step 1 you added code to calculate the LineTotal when each item is queried from the database. This works fine for initially populating the field. However, when the quantity or discountUnitPrice is changed, the LineTotal needs to be recalculated. In this step you will add code to calculate LineTotal whenever the getter method is called. You will also add code to recalculate the value whenever other values change on the line item. a. Generate a view row object for LineItem (OrderItemsViewRowImpl.java) if you have not already done so. b. Add the calculation code to the LineTotal getter method. c. Open OrderItemsViewRowImpl.java and add code to the appropriate setter methods that recalculate LineTotal. Note that adding the same code several times is not very good programming practice. Instead, add code to call setLineTotal(null), which will mark the row as 'dirty' and force the framework to perform the recalculation.
public Number getLineTotal() { return new Number(getQuantity().floatValue() * getDiscountUnitPrice().floatValue()); } public void setDiscountUnitPrice(Number value) { setLineTotal(null); setAttributeInternal(DISCOUNTUNITPRICE, value); public void setUnitPrice(Number value) { setAttributeInternal(UNITPRICE, value); setLineTotal(null); } public void setQuantity(Number value) { setAttributeInternal(QUANTITY, value); setLineTotal(null); }

Oracle9i JDeveloper: Develop Applications with BC4J B-15

Practice 7-2 (continued) d. In the View Object Wizard, change the settings for the LineTotal attribute and make this attribute updateable. e. Test your changes using the Business Component browser.

Oracle9i JDeveloper: Develop Applications with BC4J B-16

Practice 8-1 Start JDeveloper, and open the workspace practice08.jws. Simulate two users using two separate instances of your application module trying to update the same record. In the first part, you will use pessimistic locking mode, which is the default behavior. In this practice, you will use the Business Components Browser to show how different locking modes affect multiple users. In a later practice, you will add code to a client application to manipulate the locking mode. 1. Simulate multiple-user updates using pessimistic locking. a. Open and rebuild the Locking project. b. Run the Business Components browser on the application module, and designate this instance as User1. c. Run the Business Components browser on the application module again, and designate this instance as User2. You should now have two separate instances of the browser. d. In in the browser you designated as User1, check the value of Transaction.LockMode by right-clicking the application module name and selecting Properties. The value should be 1, which indicates pessimistic locking. Remember pessimistic locking is the default. e. Open an instance of OrdersView in both browsers (User1 and User2). f. Both browsers should display the same row of data. If they do not show the same record, scroll through the result set until they display the same row. g. In User1, enter a value in Promotion Id, and then tab out of the field to write the change to the entity objects cache (do not save the change).\ h. In User2, enter a different value in Promotion Id and then click the green arrow (Commit button). i. Notice the error JBO-26030: Failed to lock the record; another user holds the lock. j. Dismiss the error message, and then click the red arrow (rollback) in User1. You can now save the change to User2. k. Close both tester windows. 2. Simulate multiple-user updates using optimistic locking. a. As in the Step 1 of this exercise, run the Business Components browser on the application module twice and designate one instance as User1 and the other as User2. b. Change the value of Transaction.LockMode to optimistic in both instances of the application model. Click another property to make the change stick, and then click Close. c. Double-click OrdersView in User1 and in User2. Make sure both users are displaying the same row of data. d. In User1, enter a value in Promotion Id, and then tab out of the field to write the change to the entity objects cache (do not save the change). e. In User2, enter a value in Promotion Id, and then click the green arrow (Commit button). Notice that there is no error. f. Click the Commit button in User1. Notice the error that another user has changed the same row. g. Dismiss the error message and close both tester windows.
Oracle9i JDeveloper: Develop Applications with BC4J B-17

Practice 9-1 Start JDeveloper, and open the workspace practice9.jws and the project AppModule.jpr. 1. Remove views from the application modules data model. a. Right-click the application module and select Edit Practice10Module from the Context menu. b. Remove views from your application module until it looks like the following screenshot. Notice how the left arrow button (<) is enabled and disabled as you click through the views in the data model.

c. Click Finish to save your changes. 2. Add views to the application modules data model. Add views to your application module so that it looks like the data model in the following screenshot. OrderItemsView appears three times in this data model: As a restricted view, meaning that the data in this view depends on the value selected in the source view (in this case, ProductInformationView and OrdersView) As an unrestricted view, meaning that all rows of data are available a. In the list of available views, select one of the occurrences of OrderItemsView . In the data model, select the point where you want to insert this view. Notice that the right arrow button (>) is enabled only if you have selected a valid insertion point for your view and that there is only one valid insertion point for the view that you have selected. b. Click the right arrow button (>) to add the view to the data model. c. In the list of available views, select another occurrence of OrderItemsView . In the data model, select the valid insertion point for your view. d. Click the right arrow button (>) to add the view to the data model. The model should look like the model below.

Oracle9i JDeveloper: Develop Applications with BC4J B-18

Practice 9-1 (continued) 2.Add views to the application modules data model (continued). e. Select Finish to save your changes. f. Test your new data model in the Business Component Browser. Open an instance of each of the OrderItemsView views. Undock each of the views and navigate through some rows of each view. Notice the difference in the data that is available to you from the two different occurrences of OrderItemsView. 3. Create nested application modules. Create a root application module containing two other application modules. a. Create a new application module in the same package. In the Application Module Wizard, choose a name for your new application module, and then add whatever views you like to its data model. This screenshot shows one possible data module for your application module.

b. Still in the same package, create another application module. Call your new module RootModule and do not add any views to its data model. Instead, add two application modules: the one you created in step 3a and the one you created in step 2. c. Save your changes, and test RootModule using the Business Component Browser.

Oracle9i JDeveloper: Develop Applications with BC4J B-19

Practice 10-1 Start JDeveloper, and open the workspace practice10.jws. Take an existing BC4J application and extend it to use a new attribute in the Orders table. 1. Set up a custom environment. a. Run the customize.sql script: right-click BC4J database connection and select SQL Worksheet. Open the customize.sql file with the code editor and copy the sql statement. Paste the statement into the SQL Worksheet and click the run button. This will add a new column, ship_date, to the Orders table. b. You can expand the BC4J connection node to make sure the new column is in the Orders table. 2. Add OnlineOrders.jar to the project libraries. a. Edit the Extend.jpr project settings. b. Create a new library named OnlineOrders that points to <JDevHome>\mywork\OnlineOrders\OnlineOrders\ OnlineOrders.jar. 3. Import the OnlineOrders classes into your project. a. Right-click the Extend project and select Import Business Components. b. Use the selection wizard to drill down into the OnlineOrders.jar file from <JDevHome>\mywork\OnlineOrders\OnlineOrders\ c. Select OnlineOrders.xml from the within OnlineOrders in the .jar file. d. Test the imported application with the Business Components browser. 4. Extend the Orders entity to include a new attribute. a. Create a new package in the Extend project named extend. Do not create entity objects, view objects, or an application module for this package. b. Create a new application module that extends the OnlineOrders application module. c. Test the new module to see that it reflects the original OnlineOrders application module. d. Create a NewOrders entity that extends OnlineOrders.Orders. In the last step of the Entity Wizard, select Create Default View. e. Add the NewOrders view to the data model of your new application. f. Test the new application module using the Business Components browser. Notice the difference between the old OrdersView and the NewOrders object.. 5. Substitute the NewOrders and OrdersView objects globally. Now that you have made and tested the changes to the NewOrders entity, globally substitute it for all the occurrences in the original application. a. Edit the Extend project by right-clicking on the project node and selecting Edit. b. Substitute the NewOrders entity for the Orders entity in OnlineOrders c. Substitute the NewOrders view for the Orders view in OnlineOrders. d. Test the application using the Business Components browser. Notice that all occurrences of the CustomersView now reflect the new attribute ShipDate.

Oracle9i JDeveloper: Develop Applications with BC4J B-20

Practice 11-1 Create a new BC4J application deploy it to Oracle9iAS. To start this practice: Start JDeveloper, and open the workspace practice11.jws. 1. Create a new BC4J application. a. Create a new project containing a new bc4j application. Name the project Deploy. Select Customers, Orders, Order_Items, and Product_Information as the entity objects for this project. b. Modify the application in anyway you like. For example, you could exclude some of the columns from a default view or add some specific business logic. c. Build, save, and test your application using the Business Component browser. 2. Install and start oc4j. Before you can deploy applications to OC4J, you must install the product. This is a very simple procedure which sets the password for the administrator account (admin). a. Open a command window by clicking Start -> Run from the windows Task bar. b. Change directories to <JDev Home>j2ee\home, where <JDev Home> is the installation directory for JDeveloper. Enter the command cd <JDev Home>j2ee\home c. Once you are in that directory, enter the command: java -jar oc4j.jar install d. Enter 'admin' as the password for the administrator account. The install tool will ask you to enter it again. e. After the install is complete, which should take only seconds, start the oc4j server by entering the following command: java jar oc4j.jar 3. Create a connection to the application server. a. Right-click the application server node under Connections in the navigator and select New Connection from the context menu. b. Name the connection OC4J. c. Use admin as the username and admin as the password. This should be the same password that you used in step 2. d. Use the defaults for the rest of the properties and test the connection. If it tests successfully then continue to the next step. 4. Create a deployment profile for an EJB deployment. a. From the New Gallery, select Deployment Profiles -> Business Components EJB Session Bean Profile. b. Make sure the server connection is the same as the connection you just created and select AppModule Session Bean (BMT) as the deployment style you want to use. c. In the next step of the wizard, select the application module you want to deploy with this profile and click finish.

Oracle9i JDeveloper: Develop Applications with BC4J B-21

Practice 11-1 (continued) 5. Make your application module remotable. In this step, you modify your application module so that JDeveloper will create and manage all of the classes necessary to make this application remotable. a. Edit the application module b. Select the Remote tab and make the module remotable. c. Select AppModule Session Bean (BMT) as the remotable style for this application module and click OK 6. Deploy your application module to Oracle9iAS. a. Right-click the deployment profile you just created. b. Select Deploy from the context menu. c. JDeveloper will launch the necessary commands to deploy your application as an EJB Session Bean to the Oracle9iAS server. You can watch the commands and resulting messages in the Log window at the bottom of the JDeveloper IDE. 7. Test your deployed application using the Business Components Browser. a. Launch the tester as usual. b. Select DeployModule9iAS as the Business Components Configuration Name at the top of the Connect page of the tester. This will tell the tester where your application is deployed and how to connect. c. Click connect. d. Test your application as usual. e. Close the tester.

Oracle9i JDeveloper: Develop Applications with BC4J B-22

Practice 12-1 Start JDeveloper, and open the workspace Practice12.jws. In this practice, you will code a batch client to run against the OnlineOrders application module. The BC4J application is already created and ready for you to access from a batch client. 1. Examine and test the OnlineOrders application module. a. Open the OnlineOrders project in the navigator. b. Open OnlineOrdersModuleImpl.java and look at the code for the method ordersWithLinesOverQuantity. This method is a custom application module method that can be called by any client that has access to the application module. c. Rebuild and test the Business Components Project OnlineOrders. 2. Create a new project with a batch client that instantiates the OnlineOrders application module. a. Create a new Business Components project and name it BatchClient. When the Business Components wizard launches, you can click finish without selecting any tables for this project. You are creating this project as a Business Components project so that the necessary libraries are added by default. You could create a non BC4J project but you would have to add the bc4j libraries manually. b. Create a new Application from the New Gallery. c. Name the application BatchClient. Do not include a default frame. d. Add import statements for: oracle.jbo.client.Configuration; oracle.jbo.*; OnlineOrders.common.*; e. Create a library named OnlineOrdersPath that points to the directory that holds the OnlineOrders classes. The path is <JDevHome>\jdev\mywork\OnlineOrders\OnlineOrders\classes f. Add that library to your project. g. Replace the code "new BatchClient();" with your code to instantiate the OnlineOrders application module. The application name is OnlineOrders.OnlineOrdersModule. The configuration name is OnlineOrdersModuleLocal. h. Add a print statement at the end of the main() to display a success message when you successfully make it through the program. i Save your changes,compile and test your program. At this stage, your program does not pull any data from the database, but it should compile and run without error and display your success message. This proves that you were able to instantiate the application module. With that complete, you can begin to add code that will display data from the Business Components in the OnlineOrders application module. 3. Add code to instantiate a CustomersView object and display information about the first customer in the result set. a. Find and instantiate a CustomersView object. b. Retrieve the first instance of the CustomersView. c. Check to make sure the first row is not null. If it is null, print a message that the result set is null. d. Print the Customers Id, Name and Email address. e. Save, build, and run your program.
Oracle9i JDeveloper: Develop Applications with BC4J B-23

Practice 12-1 (continued) 4. Add code to display all of the orders for the Customer you just retrieved. a. Instantiate a rowset of orders for the current customer. Use the OrdersView attribute of the customers row. b. Check to make sure the rowset is not null. If it is not null, loop through the result set displaying the Order ID, Order Date, Order Status, Order Total, and Order Mode for each Order. c. Save, build, and run your program. 5. Write the contents of the CustomersView object as an XML stream. a. Add import statements for: import oracle.xml.parser.v2.*; import java.io.*; b. Add code to create an XMLNode object from the CustomersView object you have already instantiated. c. Create a ByteArrayOutputStream object to hold the results of node.print(). d. Convert the OutputStream to a String and display the results to the standard output stream. e. Save, build, and run your program. f. Change the parameters to the writeXML() method to (1,1), which will display only one Customer but will traverse the link to show the Orders for that Customer. g. Save, build, and run your program. h. Change the parameters to (2,1) to see the LineItems for each Order. i. Save, build, and run your program 6. In an earlier lesson, you learned about custom methods you can add to an application module. These custom methods are useful to supply information to a client without requiring the client to instantiate any views. In this step you will use a custom method to display some business information. a. Before you can access custom methods in the application module, you must cast the generic application module to an OnlineOrdersModule. You do this in the code that instantiates the application module. You must also import the OnlineOrders.common.* classes. b. Create a long variable and set it equal to the result of the application module custom method ordersWithLinesOverQuantity(4).This method counts the number of OrderItems which have ordered quantities of more than 4. c. Save, build, and run your program. d. Change the parameter to the custom method and test again to see different results.

Oracle9i JDeveloper: Develop Applications with BC4J B-24

Practice 12-1 (continued) BatchClient.java


import oracle.jbo.client.Configuration; import oracle.jbo.*; import OnlineOrders.common.*; import oracle.xml.parser.v2.*; import java.io.*; public class BatchClient { public BatchClient() { } public static void main(String[] args) { String _am = "OnlineOrders.OnlineOrdersModule"; String _cf = "OnlineOrdersModuleLocal"; OnlineOrdersModule am = (OnlineOrdersModule) Configuration.createRootApplicationModule(_am, _cf); ViewObject vo_Cust = am.findViewObject("CustomersView"); Row row_Cust = vo_Cust.first(); if (row_Cust == null) { System.out.println("No customers retrieved"); } // end of if customer is null else { //else display customer info System.out.println("Customer"); System.out.println("-----------"); System.out.println(" Id: " + row_Cust.getAttribute("CustomerId")); System.out.println("Name: " + row_Cust.getAttribute("CustFirstName") + " " + row_Cust.getAttribute("CustLastName")); System.out.println("Email: " + row_Cust.getAttribute("CustEmail")); System.out.println("Orders for this Customer"); System.out.println("--------------------------------"); // retrieve set of customer orders using the view link accessor // as a virtual attribute name RowSet rowset_Orders = (RowSet)row_Cust.getAttribute("OrdersView");

Oracle9i JDeveloper: Develop Applications with BC4J B-25

Practice 12-1 (continued) BatchClient.java (continued)


if (rowset_Orders == null) { System.out.println("This customer has no Orders"); } // end of if rowset_Orders is null else { // else display orders information while (rowset_Orders.hasNext()) { // loop through the Orders Row row_Order = rowset_Orders.next(); // get the next row in the rowset System.out.println(" ******"); System.out.println(" Order ID: " + row_Order.getAttribute("OrderId")); System.out.println(" Order Date: " + row_Order.getAttribute("OrderDate")); System.out.println(" Order Status: " + row_Order.getAttribute("OrderStatus")); System.out.println(" Order Total: " + row_Order.getAttribute("OrderTotal")); System.out.println(" Order Mode: " + row_Order.getAttribute("OrderMode")); System.out.println(""); } // end while loop through Orders } // end else display Orders information } // end of else display customer info

// write the CustomersView object to the output stream as XML XMLNode node = (XMLNode) vo_Cust.writeXML(2,1); OutputStream os = new ByteArrayOutputStream(); try { node.print(os); String XMLView = os.toString(); System.out.println(os.toString()); } catch (IOException ioex) { ioex.printStackTrace(); }

//

Call an application module custom method long result = am.ordersWithLinesOverQuantity(4); System.out.println("There are " + result + " order items with quantities over 4"); System.out.println("End of BatchClient"); }

Oracle9i JDeveloper: Develop Applications with BC4J B-26

Practice 13-1 Start JDeveloper, and open the workspace practice13.jws . 1. Create a SQL-based view object. The view object selects all of the items in the inventory that have been ordered fewer than five times in total. The query joins the inventory_item, supplier, and line_item tables. a. Open the SqlBasedView project in the Navigator pane. b. Create a new SQL-based view object named UnpopularItems. This is the only view in the project. c. This view object should return those items which have a total ordered quantity of less than 5. You can write the query or use the query below for the new view object. SELECT product_name , product_description , total FROM (SELECT prod.product_name , prod.product_description , sum(nvl(order_items.quantity,0)) as total FROM product_information prod , order_items WHERE prod.product_id = order_items.product_id GROUP BY prod.product_name, prod.product_description HAVING sum(nvl(order_items.quantity,0)) < 5 ORDER BY total) d. Create a new application module for the project and name it SQLBasedViewModule. Include the UnpopularItems view object in the data model e. Run the Business Components browser and test your SQL-based view. You should see 13 items that five or fewer have been ordered. 2. Create a view object that uses a parameter. The new view object contains inventory items that have less than a specified quantity on hand. The quantity is passed to the query as a run-time parameter. a. Create a new SQL-based ViewObject named InventoryLevelView. The query will join the inventories and product_information tables. It will also sum the quantity_on_hand column from the inventories table since each item can have multiple rows. It should return return the product_id, product_name, and a sum of quantity_on_hand values from the inventory_item table. It should return only those rows where the total onhand quantity is less than the parameter value. You could code the query or use the following query.

Oracle9i JDeveloper: Develop Applications with BC4J B-27

Practice 13-1 (continued) SELECT product_id , product_name , total_on_hand FROM (SELECT prod.product_id , prod.product_name , sum(nvl(inv.quantity_on_hand,0)) as total_on_hand FROM product_information prod , inventories inv WHERE prod.product_id = inv.product_id GROUP BY prod.product_id , prod.product_name HAVING sum(nvl(inv.quantity_on_hand,0)) < 200 ORDER BY total_on_hand) b. Add the view object to the application module and test it with the business components browser. c. Replace the hard coded value 200 with a parameter placeholder. 3. Create a batch client program to test the parameter based query. a. Create a new Application from the New Gallery. b. Name the application TestClient. Do not include a default frame. c. Add import statements for: oracle.jbo.client.Configuration; oracle.jbo.*; d. Replace the code "new TestClient();" with your code to instantiate the SQLBasedView application module. The application name is SQLBasedView.SQLBasedView . The configuration name is SQLBasedViewModuleLocal. e. Add a print statement at the end of the main() to display a success message when you successfully make it through the program. f. Save your changes,compile and test your program. At this stage, your program does not pull any data from the database, but it should compile and run without error and display your success message. This proves that you were able to instantiate the application module. With that complete, you can begin to add code that will display data from the Business Components in the SQLBasedView application module. g. Create a string object named howManyStr to hold the value of the command-line argument. h. Add code to make sure an argument is passed. If the program does not receive an argument, display an appropriate error message and quit the application. If there is an argument, set howManyStr to the value and display the value.

Oracle9i JDeveloper: Develop Applications with BC4J B-28

Practice 13-1 (continued) i. Add code to instantiate the InventoryLevelView object and set its Where clause parameter to the value of the argument from the command line and execute the query on the view object. j. Add a loop to display all of the rows of the view object displaying the product_id, product_name, and total_on_hand k. Modify the project properties to pass a command line argument to your program by editing project properties and selecting the Development ->Runner node. Enter a number in the program argument field. l. Build, save, and test your program.

Oracle9i JDeveloper: Develop Applications with BC4J B-29

Practice 13-1 (continued) TestClient.java


import oracle.jbo.client.Configuration; import oracle.jbo.*; public class TestClient { public TestClient() { } public static void main(String[] args) { String howManyStr = null; if (args.length == 0) { System.out.println("You must enter a value for minimum inventory level"); System.exit(1); } else { howManyStr = args[0]; System.out.println("This will show items with less than " + howManyStr + " items in stock"); } String _am = "SQLBasedViewSoln.SQLBasedViewSoln", _cf = "SQLBasedViewSolnModuleLocal"; ApplicationModule am = Configuration.createRootApplicationModule(_am,_cf); ViewObject vo_Inv = am.findViewObject("InventoryLevelView"); vo_Inv.setWhereClauseParam(0,howManyStr); vo_Inv.executeQuery(); // Add code here to work with application module while (vo_Inv.hasNext()) { Row row_Inv = vo_Inv.next(); System.out.println("Product Id: " + row_Inv.getAttribute("ProductId")); System.out.println("Product Name: " + row_Inv.getAttribute("ProductName")); System.out.println("Total On Hand: " + row_Inv.getAttribute("TotalOnHand")); } } }

Oracle9i JDeveloper: Develop Applications with BC4J B-30

Practice 14-1 Start JDeveloper, and open the workspace Practice14.jws. In this practice, build a JSP application that uses data tags. The JSP application uses the OnlineOrders business components application as its datasource. The JSP application will display a list of all Customers 1. Create a new project named JSPClient with a JSP client that uses the CustomersView from the OnlineOrders application module as its datasource. a. Create a new empty project named JSPCLient. b. Create a new JSP in the JSPClient project by selecting JSP from the Web Objects category in the New gallery. Name the JSP Customers.jsp. c. Edit the source code of the Customers.jsp. Beneath the closing </p> tag, use the component palette to insert an ApplicationModule data tag to point to the OnlineOrders business components application d. Next, add a Data Source data tag from the component palette based on the CustomersView object. Name the datasource dsCustomers and click Finish to generate the tag. 2. Create a table for displaying the names of Customers. Use an html table and the RenderValue and RowSetIterate data tags. a. Create an html table using the <table border=1> tag. The end </table> tag will be automatically generated for you. b. Between the beginning and end table tags, insert a RowSetIterate data tag from the component palette. This tag will iterate through the datasource. c. Between the beginning and end RowSetIterate tags, insert a new table row using <tr> d. Between the beginning and end <tr> tags, insert new columns using the <td> tag. e. Insert a RenderValue data tag between the beginning and end <td> tags to display the values of the CustomerId attributes in the dsCustomers data source. f. Insert additional RenderValue tags for the CustFirstName and CustLastName attributes. 3. Test the application by right-clicking on Customers.jsp and selecting Run. The id, first name, and last name of each customer in the Customers ViewObject should be displayed in an html table in the browser.

Oracle9i JDeveloper: Develop Applications with BC4J B-31

Practice 14-1 Customers.jsp


<%@ taglib uri="/webapp/DataTags.tld" prefix="jbo" %> <%@ page contentType="text/html;charset=windows-1252"%> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"> <TITLE> Hello World </TITLE> </HEAD> <BODY> <H2> The current time is: </H2> <P> <% out.println((new java.util.Date()).toString()); %> </P> <jbo:ApplicationModule id="OnlineOrdersModule" configname="OnlineOrders.OnlineOrdersModule.OnlineOrdersModuleLocal" releasemode="Stateful" /> <jbo:DataSource id="dsCustomers" appid="OnlineOrdersModule" viewobject="CustomersView" /> <table border=1> <jbo:RowsetIterate datasource="dsCustomers" > <tr> <td><jbo:RenderValue datasource="dsCustomers" dataitem="CustomerId" ></jbo:RenderValue></td> <td><jbo:RenderValue datasource="dsCustomers" dataitem="CustFirstName" ></jbo:RenderValue></td> <td><jbo:RenderValue datasource="dsCustomers" dataitem="CustLastName" ></jbo:RenderValue></td> </tr> </jbo:RowsetIterate> </table> </BODY> </HTML> <jbo:ReleasePageResources />

Oracle9i JDeveloper: Develop Applications with BC4J B-32

Practice 14-2 In this practice, you will create a BC4J-based JSP application using the wizards and customize the generated JSP application to view the data in a master-detail format. 1. First, create a form for browsing and editing the OrdersView object in JSPClient project. a. Create a new data page form using the BC4J JSP wizard by selecting Browse and Edit Form from the BC4J JSP Category in the New Gallery. b. Select the OnlineOrders application and OrdersView as the view object for this form. When you click Finish, the wizard will generate several files for you. OrdersView_BrowseEdit.jsp is the main form for browsing and editing. This file uses three component tags, DataHandler, DataScroller, and DataTable. Additional files are added for editing the OrdersView attributes, and for using Intermedia data types. c. Double-click OrdersView_BrowseEdit.jsp in the navigator to display the code in the code editor. Notice that the ApplicationModule and DataSource data tags are used to link the JSP to a View Object. Additionally, the DataTableComponent.jsp contains RowSetIterate and RenderValue tags for displaying ViewObject attributes. d. Right-click OrdersView_BrowseEdit.jsp and select Run to test the functionality of the form. 2. Next, create a form for browsing the OrderItems ViewObject. a. Create a new form in the JSPClient project by selecting Browse Form from the BC4J JSP Category in the New Gallery. b. Base this form on the OrderItemsView1 ViewObject. This View will be in sync with it's master form. The OrderItemsView1 ViewObject is in the OnlineOrders application module. Note that the component JSP pages were added to your project by the wizard in step 1. The OrderItems Browse form and the Orders Browse and Edit form have several of these component tags in common. Therefore, they will be overwritten when the second form is generated. Click Yes to overwrite each of the JSP pages. 3. Finally, link the two forms together so that the details can be retrieved from the master form. To do this, you will modify the master JSP to include a link for viewing that record's detail. You will also modify the detail JSP to display the detail records based on the row selected in the master JSP. You will make these modifications in the DataTableComponent.jsp and OrderItemsView_Browse.jsp a. First, save the DataTableComponent.jsp as DataTableComponentMaster.jsp. To do this, you must trick the IDE into thinking the file has been modified. Edit the DataTableComponent.jsp. and insert a space anywhere in DataTableComponent.jsp and then delete the space. That will mark the file as changed. You can now select Save As from the file menu and save the file as DataTableComponentMaster.jsp. b. Modify OrdersView_BrowseEdit.jsp to use the new component tag by adding the following attribute to the jbo:DataTable tag: relativeUrlPath="DataTableComponentMaster.jsp"

Oracle9i JDeveloper: Develop Applications with BC4J B-33

Practice 14-2 (continued) c. Next, add a link for viewing details in the master component tag. d. Locate the href link tags in DataTableComponentMaster.jsp for deleting and editing records. These are similar to the link you will be creating to OrderItemsView1_Browse.jsp. e. Add the following code between the end </td> and the opening scriptlet (<%) of the UrlEvent named Edit. <td> <a href="<jbo:UrlEvent targeturl='OrderItemsView1_Browse.jsp' event='details' addrowkey='true' />">View Detail</a> </td> f. This adds a link to the end of the row and passes the row key for the current row to the OrderItemsView1_Browse.jsp. 4. Next, create the URLEvent details, that is called from the href link. a. Open the OrderItemsView1_Browse.jsp in the editor. b. Add the following code after the <jbo:DataHandler appid="am" /> tag: <jbo:OnEvent name="details"> <jbo:DataSource id="dsOrders" appid="am" viewobject="OrdersView" /> <jbo:Row id="myrow" datasource="dsOrders" rowkeyparam="jboRowKey" action="Find" /> </jbo:OnEvent> Note: This creates a new event named details which finds the current row for the selected master record, using the datasource and rowkeyparam attributes c. Build JSPClient.jpr and run OrdersView_BrowseEdit.jsp to test the new functionality.

Oracle9i JDeveloper: Develop Applications with BC4J B-34

Practice 14-2 (continued) OrdersView_BrowseEdit.jsp


<%@ page language="java" errorPage="errorpage.jsp" contentType="text/html;charset=windows-1252" %> <%@ taglib uri="/webapp/DataTags.tld" prefix="jbo" %> <html> <head> <META NAME="GENERATOR" CONTENT="Oracle JDeveloper"> <LINK REL=STYLESHEET TYPE="text/css" HREF="/webapp/css/bc4j.css"> <TITLE>Browse Form</TITLE> </head> <body> <jbo:ApplicationModule id="am" configname="OnlineOrders.OnlineOrdersModule.OnlineOrdersModuleLocal" releasemode="Stateful" /> <jbo:DataSource id="ds" appid="am" viewobject="OrdersView" rangesize="3"/> <jbo:DataHandler appid="am" /> <jbo:DataTransaction appid="am" /> <h3>OrdersView Browse Form</h3> <table border="0"> <tr> <td ALIGN="right"><jbo:DataScroller datasource="ds" /></td> </tr> <tr> <td><jbo:DataTable datasource="ds" edittarget="OrdersView_Edit.jsp" relativeUrlPath="DataTableComponentMaster.jsp" /></td> </tr> </table> <jbo:ReleasePageResources /> </body> </html>

Oracle9i JDeveloper: Develop Applications with BC4J B-35

Practice 14-2 (continued) DataTableComponentMaster.jsp


<%@ page language="java" import = "oracle.jbo.html.*, oracle.jbo.*" %> <%@ taglib uri="/webapp/DataTags.tld" prefix="jbo" %> <%-- This JSP component display a table bound to a datasource and links to an edit form. It is called by the DataTable tag --%> <% // Retrieve all request parameters using our routine to // handle multipart encoding type RequestParameters params = HtmlServices.getRequestParameters(pageContext); String editTargetParam = params.getParameter("edittarget"); if ("null".equalsIgnoreCase(editTargetParam)) { editTargetParam = null; } %> <%-- Restore the data binding to the datasource passed as parameter --%> <jbo:DataSourceRef id="dsBrowse" reference='<%=params.getParameter("datasource")%>' /> <%-- Display the current rows in a grid with a column for each attr --%> <table class="clsTable" cellspacing="1" cellpadding="3" border="0"> <tr class="clsTableRow"><% if (editTargetParam != null) { %> <th class="clsTableHeader">&nbsp;</th> <th class="clsTableHeader"><a href="<jbo:UrlEvent targeturlparam='edittarget' event='Create' datasource='dsBrowse' extraparameters='<%="originURL=" + params.getParameter("originURL")%>'/>">New</a></th><% } %> <%-- Display all the attribute names in the table header --%> . <jbo:AttributeIterate id="df" datasource="dsBrowse"> <th title="<jbo:ShowHint hintname='TOOLTIP'/>" class="clsTableHeader"><jbo:ShowHint hintname="LABEL">##Column</jbo:ShowHint></th> </jbo:AttributeIterate> </tr><% // Retrieve the current row to match it again all the other row // of the range and display it in a different color. Row currentRow = dsBrowse.getRowSet().getCurrentRow(); %>

Oracle9i JDeveloper: Develop Applications with BC4J B-36

Practice 14-2 (continued) DataTableComponentMaster.jsp (continued)

<%-- Iterate through rows in the range without changing the currency --%> <jbo:RowsetIterate datasource="dsBrowse" changecurrentrow="false" userange="true"> <jbo:Row id="aRow" datasource="dsBrowse" action="Active"/><% String rowStyle; if (aRow == currentRow) rowStyle = "clsCurrentTableRow"; else rowStyle = "clsTableRow"; %> <tr class="<%=rowStyle%>"><% if (editTargetParam != null) { %> <td> <a href="<jbo:UrlEvent targeturlparam='originURL' event='Delete' datasource='dsBrowse' addrowkey='true'/>">Delete</a> </td> <td> <a href="<jbo:UrlEvent targeturlparam='edittarget' event='Edit' datasource='dsBrowse' addrowkey='true' extraparameters='<%="originURL=" + params.getParameter("originURL")%>'/>">Edit </a> </td><% } %><%-- Iterate through attributes of the row and Render value --%> <jbo:AttributeIterate id="dfv" datasource="dsBrowse"> <td title="<jbo:ShowHint hintname='TOOLTIP'/>" > <jbo:RenderValue datasource="dsBrowse">##Cell</jbo:RenderValue> </td> </jbo:AttributeIterate> <td> <a href="<jbo:UrlEvent targeturl='OrderItemsView1_Browse.jsp' event='details' addrowkey='true' />">View Detail</a></td> . </tr> </jbo:RowsetIterate> </table>

Oracle9i JDeveloper: Develop Applications with BC4J B-37

Practice 15-1 Start JDeveloper, and open the workspace practice15.jws In this practice, you will create a BC4J-based JClient application using the wizards.The application is a master-detail form. You will also deploy the application as a standalone java application. 1. Create a JClient Data Model a. In the Navigator select the JClient project. b. Open the New Gallery c. Select JClient Objects -> JClient Data Model. d. Accept the default business component project, and application which should be OnlineOrders.OnlineOrdersModule. e. Accept the default client data model name. f. Click Finish when done. 2. Create a JClient Form Now that you have a JClient Data Model, you can create a JClient form that uses the Data Model. a. Open the New Gallery in the JClient project b. Select JClient Objects -> JClient Form to invoke the JClient Form wizard. c. Select Master-Detail Tables as the type of form and Frame as the implementation style. d. Select Master and Detail templates. You may accept the default values or choose whichever you think will look and behave the best. e. Accept the OnlineOrdersModule as the Data Model for this form. f. Select the CustomersView as the Master object and OrdersView1 as the detail object. g. Select the following attributes for the CustomersView:

CustomersId CustFirstName CustLastName CustAddress CreditLimit Status


h. Select the following attributes for the OrdersView:

OrderId OrderDate OrderMode OrderStatus OrderTotal


i. Change the package name to JClient. j. Click Finish when done k. Build, save, and test your project. To test your application , right-click FrameCustomersViewOrdersView1.java and select run from the context menu.
Oracle9i JDeveloper: Develop Applications with BC4J B-38

Practice 15-1 (continued)

Oracle9i JDeveloper: Develop Applications with BC4J B-39

Practice 15-1 (continued) 3. Create a deployment profile for your application. a. Create a new Deployment Profile from the New Gallery, select JAR file Simple Archive. Accept the default name or choose a different name. b. In the Files node, select the files you want to include in the archive. For our purposes, select all the files. c. In the JAR options, make sure Include Manifest File is selected. Be sure the enter the fully qualified location of the Main Class. For example: JClient.FrameCustomersViewOrdersView1 d. In the Dependency Analyzer node, select the libraries you want to repackage into your .jar file. Include the following libraries: Business Component Libraries (your workspace classes) JClient Runtime bc4jui.jar JDeveloper Runtime all libraries BC4J Runtime all libraries Oracle JDBC all libraries Connection Manager all libraries BC4J Oracle Domains all libraries e. Click OK to finish creating the deployment profile 4. Deploy the application. a. Right-click the deployment profile you just created and select Deploy to from the context menu. b. Accept the default location for your deployment which is the same as your project directory. Enter a name for the .jar file. You could use the project name for example. c. You have now deployed your JClient application. 5. Test your deployed application. a. Open a command window be clicking on the Windows Start button and selecting Run. Enter cmd in the Open field and click OK. b. In the command window, change to the directory that holds the JDK. That directory is <JDevHome>\jdk\bin. To change directories in a command window, type CD followed by the directory name. c. Once you are in the correct directory start your application by running java with an argument that points to your deployed application. The command is:
java -jar <JDevHome>\jdev\mywork\Practice15\JClient\<MyJar>.jar

(Where <JDevHome> is the name of the directory in which JDeveloper is installed, and <MyJar> is the name you chose for the application deployment .jar file).

Oracle9i JDeveloper: Develop Applications with BC4J B-40

Potrebbero piacerti anche