Developing SQL and PL/SQL with JDeveloper

This tutorial shows you how to develop, tune, and debug the SQL and PL/SQL portions of an application with JDeveloper.

Topics

The tutorial will discuss the following:

Overview
Prerequisites
Browsing the Database

Creating and Compiling PL/SQL

Executing and Tuning SQL Statements
Creating and Deploying a Java Stored Procedure

Debugging a PL/SQL Subprogram and Java Stored Procedure

Summary

60 minutes

Move your mouse over this icon to show all screenshots. You can also move your mouse over each individual icon to see only the screenshot associated with it.

Overview

JDeveloper provides functionality to view and modify database objects, including stored procedures. In this lesson you create and modify both PL/SQL and Java stored procedures. You deploy Java stored procedures and call them from PL/SQL. You also use JDeveloper to execute and tune SQL statements and debug stored procedures.

Back to Topic List

You have existing PL/SQL and Java stored procedures that you want you manage with JDeveloper. You also want to use JDeveloper to tune SQL statements, create and deploy new Java stored procedures, and create and debug PL/SQL stored procedures.

Prerequisites

Back to Topic List

In order for this tutorial to work successfully, you will need to have performed the following:

1.

Install Oracle JDeveloper 10g.

 

2.

Install the Oracle Sample Schemas and create a connection to the HR or HR8 schema. See Installing the Sample Schemas and Establishing a Database Connection.

 

3 .

For the PL/SQL debugging portion of this tutorial, the HR or HR8 user needs special debug privileges if the database is Oracle 9i Release 2 or later.

To grant the necessary privileges, the DBA user can issue the following SQL statement:
GRANT debug any procedure, debug connect session TO hr;

 

Browsing the Database

Back to Topic List

There are several ways that you can use JDeveloper to browse database objects. This topic discusses the following subtopics:

Browsing Database Objects Owned by the Current User

Browsing Database Objects Owned by Other Users
Filtering Database Objects for Browsing

Browsing a Table

Browsing Database Objects Owned by the Current User

Back to List

This topic assumes that you have already defined a database connection to the HR or HR8 user, as described in Prerequisites. The example uses MyHRConn for the name of that connection, but if you have used a different name, just select the connection that you defined.

To browse database objects owned by the current user, perform the following steps:

1.

Select View | Connections Navigator.

Move your mouse over this icon to see the image

 

2.

Expand the Database node to show all database connections. Expand MyHRConn. By default, only the database objects owned by the current user are displayed.

Move your mouse over this icon to see the image

 

Browsing Database Objects Owned by Other Users

Back to List

To browse database objects owned by other users, perform the following steps:

1.

Right-click MyHRConn and select Apply Filter from the context menu.

Move your mouse over this icon to see the image

 

2.

Select OE from the Available Schemas list and move it to the Displayed Schemas list.

Move your mouse over this icon to see the image

 

3.

Click OK. You should now see both the HR and OE schemas.

Move your mouse over this icon to see the image

Filtering Database Objects for Browsing

Back to List

You can filter out objects you don't need to browse. This is especially useful for schemas which may contain thousands of objects. To filter out classes of database objects, perform the following steps:

1.

Expand the OE node in the Connections Navigator. Expand the Synonyms node. By default only your private synonyms are shown.

Move your mouse over this icon to see the image

 

2.

Right click on the Synonyms node and choose Apply Filter from the context menu.

Move your mouse over this icon to see the image

 

3.

Enter USER% in the Filter Text field (this is case sensitive). Check the Show Public Synonyms check box.

Move your mouse over this icon to see the image

 

4.

Click OK. You should now be able to see all the public synonyms whose names begin with USER.

Move your mouse over this icon to see the image

 

Note: There's another way to find what you are looking for in the Navigator. With the Navigator in focus, you can simply begin typing the name of the node you are looking for. JDeveloper will automatically navigate you to the first node it finds starting with the text you've typed in.

When working with many objects in the navigator, it may be difficult to find the node you are looking for. JDeveloper provides filters at every level of a database connection to limit the number of objects you need to look through. You've already seen one example of a filter when you selected which schemas you wanted to view.

Browsing a Table

Back to List

To browse a table in the HR schema and its data, perform the following steps:

1.

Expand the HR node in the Connections Navigator (the remainder of this lesson pertains to the HR schema). Expand the Tables node.

Move your mouse over this icon to see the image

 

2.

Double-click the EMPLOYEES table to open the table in the Table Viewer.


Move your mouse over this icon to see the image

The Table Viewer shows information about the table, including column names and data types, primary keys, and Not Null constraints. Additionally, information about indexes on the selected table is displayed in the Structure Pane ( Note that this is not the Structure tab in the Table Viewer, but the Structure Pane that opens in the left section of the JDeveloper user interface).

 

3.

Click the Data tab in the Table Viewer. By default, the Table Viewer fetches 100 rows at a time.

Move your mouse over this icon to see the image

 

4.

Change the Fetch Size to 10.

Move your mouse over this icon to see the image

 

5.

Click Refresh to re-execute the query. This time you will only see the first ten rows.

Move your mouse over this icon to see the image

 

6.

Click Fetch Next to retrieve the next 10 rows.

Move your mouse over this icon to see the image

 

Creating and Compiling PL/SQL

Back to Topic List

To create, edit, compile, and test a PL/SQL procedure, perform the following steps:

1.

Create the PL/SQL procedure: Right-click on the Procedures node in the Connections Navigator and choose New PL/SQL Procedure.

Move your mouse over this icon to see the image

Enter emp_list as the Object Name. Click OK.

Move your mouse over this icon to see the image

JDeveloper creates a skeleton procedure.

 

2.

Edit the PL/SQL procedure. Copy and paste the following code into the PL/SQL editor:

PROCEDURE EMP_LIST(pMaxRows NUMBER)
AS
    CURSOR emp_cursor IS
        SELECT l.state_province, l.country_id, d.department_name, e.last_name,
          j.job_title, e.salary, e.commission_pct
        FROM locations l, departments d, employees e, jobs j
        WHERE l.location_id = d.location_id
          AND d.department_id = e.department_id
          AND e.job_id = j.job_id;
    emp_record emp_cursor%ROWTYPE;
    TYPE emp_tab_type IS TABLE OF emp_cursor%ROWTYPE INDEX BY BINARY_INTEGER;
    emp_tab emp_tab_type;
    i NUMBER := 1;
    JavaSPReturn VARCHAR2(50);
BEGIN
    OPEN emp_cursor;
    FETCH emp_cursor INTO emp_record;
    emp_tab(i) := emp_record;
-- add Java stored procedure call here --
    WHILE ((emp_cursor%FOUND) AND (i < pMaxRows) LOOP
        i := i + 1;
        FETCH emp_cursor INTO emp_record;
        emp_tab(i) := emp_record;
    END LOOP;
    CLOSE emp_cursor;
    FOR j IN REVERSE 1..i LOOP
        DBMS_OUTPUT.PUT_LINE(emp_tab(j).last_name);
    END LOOP;
    DBMS_OUTPUT.PUT_LINE(JavaSPReturn);
END;


Note: This code contains a syntax error that you will discover in the next section.

Move your mouse over this icon to see the image

 

3.

There are several ways to find syntax errors. To detect the syntax error in your sample code, perform one of the following:

 

Select View > Structure to display the Structure Pane, then expand the Errors node. You can then navigate to the detected error by double-clicking the error.

Move your mouse over this icon to see the image


 

Place your cursor next to one of the parentheses in the WHILE statement. JDeveloper highlights the matching symbol for the parenthesis at the cursor. If you place your cursor next to the first parenthesis in the statement, you will notice that it is highlighted in red which indicates that it does not have a matching symbol.

Move your mouse over this icon to see the image

 

 

Compile the PL/SQL subprogram by clicking the Save button in the toolbar. Compilation errors are shown in the log window. You can navigate to the line reported in the error by double-clicking on the error.

Move your mouse over this icon to see the image

Note that when an invalid PL/SQL subprogram is detected by JDeveloper, the status is indicated with a red X over the icon for the subprogram in the Connections Navigator:

 

4.

Fix the syntax error: Add the missing ) at the end of the WHILE statement just after pMaxRows and before the LOOP keyword. Click the Save button Save button in the toolbar. You should see a message in the status bar indicating a Successful compilation.

Move your mouse over this icon to see the image

 

5.

Run the PL/SQL procedure: Right-click the procedure and choose Run from the context menu.

Move your mouse over this icon to see the image

 

6.

This invokes the Run PL/SQL dialog. The Run PL/SQL dialog enables you to select the target procedure or function to run (useful for packages) and displays a list of parameters for the selected target. In the PL/SQL block text area is some generated code that JDeveloper uses to call the selected program. You can use this area to populate parameters to be passed to the program unit and to handle complex return types.

In the PL/SQL Block replace PMAXROWS := NULL; with PMAXROWS := 5;

Move your mouse over this icon to see the image

 

7.

Click OK. You should see the results of the 5 rows returned in the Log window.

Move your mouse over this icon to see the image

 

Executing and Tuning SQL Statements

Back to Topic List

You can use JDeveloper to improve performance of SQL statements. This topic discusses the following subtopics:

Executing a SQL Statement

Retrieving the Explain Plan for a SQL Statement
Tuning a SQL Statement

Executing a SQL Statement

Back to List

To execute a SQL statement, perform the following steps:

1.

Right-click on the MyHRConn node in the Connections Navigator and choose SQL Worksheet from the context menu..

Move your mouse over this icon to see the image

 

2.

Enter a simple statement, such as: SELECT * FROM employees;


Move your mouse over this icon to see the image

 

3.

Click the Execute Statement button.

Move your mouse over this icon to see the image

 

Retrieving the Explain Plan for a SQL Statement

Back to List

To retrieve the explain plain for a SQL statement, perform the following steps:

1.

Delete the SQL statement from the SQL Worksheet.

Move your mouse over this icon to see the image

 

2.

If the EMP_LIST source is no longer visible, double-click the EMP_LIST node to open the procedure in the code editor. Highlight the SELECT statement from the cursor declaration and copy it to the clipboard (Ctrl+C).

SELECT l.state_province, l.country_id, d.department_name, e.last_name,
j.job_title, e.salary, e.commission_pct
FROM locations l, departments d, employees e, jobs j
WHERE l.location_id = d.location_id
AND d.department_id = e.department_id
AND e.job_id = j.job_id;

Move your mouse over this icon to see the image

3.

Paste (Ctrl+V) the SELECT statement into the SQL Worksheet. Click the Execute Statement button.

Move your mouse over this icon to see the image

You should see the results of the statement.

 

4.

Click the Execute Explain Plan button.

Note: If you do not have a PLAN_TABLE in the current schema, you will be prompted to create it. In this case, simply click OK to create the PLAN_TABLE.

JDeveloper displays the results of the SQL explain plan.

By default, the system most likely performs a full table scan on all the tables as shown in the Explain Plan Results section in the following illustration:

Move your mouse over this icon to see the image

Note: If your results are significantly different from those shown, it may be because the schema has not been analyzed. To analyze the schema, enter and execute the following in the SQL Worksheet, then try again:

BEGIN
DBMS_UTILITY.ANALYZE_SCHEMA('HR', 'COMPUTE');
END;

 

Tuning a SQL Statement

Back to List

There are several techniques to improve performance of a SQL statement. One of these is to specify that the server should quickly retrieve and display the first set of rows. To add a FIRST_ROWS hint to a SQL statement, perform the following steps:

1.

Edit the SQL statement to include the optimizer hint   FIRST_ROWS. In this case, you should see a visible difference in the explain plan by requesting the server to retrieve the first set of rows as quickly as possible.

After inserting the FIRST_ROWS optimizer hint, the query should appear as follows:

SELECT /*+ FIRST_ROWS */ l.state_province, l.country_id,
d.department_name, e.last_name,
j.job_title, e.salary, e.commission_pct
FROM locations l, departments d, employees e, jobs j
WHERE l.location_id = d.location_id
AND d.department_id = e.department_id
AND e.job_id = j.job_id
;

Move your mouse over this icon to see the image

 

2.

Click the Execute Explain Plan button. You should now see a different explain plan that uses one or more indexes for data retrieval.

Move your mouse over this icon to see the image

 

Creating and Deploying a Java Stored Procedure

Back to Topic List

JDeveloper simplifies deployment of Java stored procedures and allows debugging of Java stored procedures. You will create a new Java class as the basis for the Java stored procedure, then deploy it to the database.

This topic presents the following subtopics:

Creating a New Application Workspace

Creating a New Java Class for the Stored Procedure
Creating a New Deployment Profile
Creating a New PL/SQL Wrapper Definition
Deploying the Java Stored Procedure
Testing the Java Stored Procedure

Creating a New Application Workspace

Back to List

To create a new application workspace in JDeveloper, perform the following steps:

1.

In the Applications Navigator, right click on the Applications node and choose New Application Workspace from the context menu.

Move your mouse over this icon to see the image

 

2.

Enter DBApplication as the Application Name. Select No Template [All Technologies] as the Application Template. You can enter a package name of your choice or leave the default package name.

Move your mouse over this icon to see the image

Click OK.

 

Creating a New Java Class for the Stored Procedure

Back to List

To create a new Java class, perform the following steps:

1.

Select the Project node in the Applications Navigator. Choose File > New from the main menu.

Move your mouse over this icon to see the image

 

2.

In the New Gallery, select General from the Categories list on the left side, and Java Class from Items on the right.

Move your mouse over this icon to see the image

Click OK.

 

3.

Enter JavaStoredProc as the name of the new Java class.

Move your mouse over this icon to see the image

Click OK.

 

4.

Write the code for the Java stored procedure. You can write any Java code with a public static method for your Java stored procedure. In this case, you can copy and paste the following:

public class JavaStoredProc
{

public JavaStoredProc()
{
}

public static String getHelloFromJava ()
{
    String _string = new String();
    for (int i = 0; i < 3 ; i++)
    {
        _string = _string + "Hello World ";
    }
    return _string;
    }
}

Move your mouse over this icon to see the image

Choose File > Save All from the main menu to save your work.

 

Creating a New Deployment Profile

Back to List

To create a deployment profile for the Java stored procedure, perform the following steps:

1.

Select the Project node in the Applications Navigator. Right-click and choose Make from the context menu.

Move your mouse over this icon to see the image

 

2.

Choose File > New from the main menu. Select the General > Deployment Profiles category.
Select the Loadjava and Java Stored Procedures profile and click OK.

Move your mouse over this icon to see the image

 

3.

Enter MyJavaSPProfile.deploy as the Deployment Profile Name and click OK.

Move your mouse over this icon to see the image

 

4.

Click OK to accept the default values in the Deployment Profile Properties window.

Move your mouse over this icon to see the image

 

Creating a New PL/SQL Wrapper Definition

Back to List

In order to execute the Java stored procedure from SQL or PL/SQL, a PL/SQL wrapper is required. To create a PL/SQL wrapper for the Java stored procedure, perform the following steps:

1.

Select MyJavaSPProfile.deploy in the Applications Navigator. Right click and choose Add Stored Procedure from the context menu.

Move your mouse over this icon to see the image

 

2.

Select the getHelloFromJava() method.


Move your mouse over this icon to see the image

Click OK. Choose File > Save All from the main menu.

 

Deploying the Java Stored Procedure

Back to List

To deploy the Java stored procedure, perform the following steps:

1.

Select MyJavaSPProfile.deploy in the Applications Navigator. Right click and choose Deploy to > MyHRConn from the context menu.

Move your mouse over this icon to see the image

 

2.

Verify that the deployment completed successfully. Check for a success message in the Log window:


Invoking loadjava on connection 'MyHRConn' with arguments:
-order -resolve -thin
Loadjava finished.
Executing SQL
Statement:
CREATE OR REPLACE FUNCTION getHelloFromJava RETURN VARCHAR2
AUTHID CURRENT_USER AS LANGUAGE JAVA NAME 'JavaStoredProc.getHelloFromJava()
return java.lang.String';
Success.
Publishing finished.
---- Stored procedure deployment finished. ----

Move your mouse over this icon to see the image

Testing the Java Stored Procedure

Back to List

To test the Java stored procedure deployment, perform the following steps:

1.

Expand the Functions node in the Connections Navigator. Right click on the GETHELLOFROMJAVA node and choose Run from the context menu. (If you are unable to see the GETHELLOFROMJAVA node, then select View > Refresh from the JDeveloper menu.)

Move your mouse over this icon to see the image

 

2.

In the Run PL/SQL window, click OK.

Move your mouse over this icon to see the image

 

3.

Confirm that the output v_Return = Hello World Hello World Hello World appears in the Log window.

Move your mouse over this icon to see the image

 

Debugging a PL/SQL Subprogram and Java Stored Procedure

Back to Topic List

JDeveloper supports PL/SQL debugging with Oracle databases. Debugging Java stored procedures is available only with Oracle9i Release 2 and later.

This topic includes the following subtopics:

Modifying the PL/SQL to Call the Java Stored Procedure

Debugging the PL/SQL Procedure
Stepping through the Code
Modifying the PL/SQL Procedure at Runtime

Modifying the PL/SQL to Call the Java Stored Procedure

Back to List

To modify the PL/SQL procedure to call the Java stored procedure, perform the following steps:

1.

In the Connections Navigator, expand the MyHRConn connection, the HR node, and the Procedures node. Double-click EMP_LIST to open it in the code editor.

Move your mouse over this icon to see the image

 

2.

Look for the line of code in the EMP_LIST procedure:
-- add Java stored procedure call here --

Just below this line, add the following:
JavaSPReturn := getHelloFromJava;

Click the Save button in the toolbar.


Move your mouse over this icon to see the image

Debugging the PL/SQL Procedure

Back to List

To debug the PL/SQL procedure, perform the following steps:

1.

Set a breakpoint in the EMP_LIST procedure by clicking in the margin at the line with the OPEN emp_cursor; statement

Move your mouse over this icon to see the image

 

2.

Right-click on the EMP_LIST node in the Connections Navigator and choose Debug.

Move your mouse over this icon to see the image

Note: If you receive the error "ORA-30683: failure establishing connection to debugger", and if you are using a Virtual Private Network (VPN) to connect to the database, you must set JDeveloper to prompt for the host IP address. Choose Tools > Preferences, select the Debugger node, and select the check box labeled Prompt for Debugger Host for Database Debugging. Then when you run the debugger, enter the VPN IP address when prompted.

 

3.

In the Debug PL/SQL dialog, click OK. The debugger should halt at the line where you placed the breakpoint. You can now control the flow of execution, modify values of variables and perform other debugging functions.

Move your mouse over this icon to see the image

Note: If at this point you receive the error message "This session requires DEBUG CONNECT SESSION and DEBUG ANY PROCEDURE user privileges", you need to complete Step 3 of Prerequisites.

 

Stepping through the Code

Back to List

To step through the code of the PL/SQL procedure, perform the following steps:

1.

Click Step Into . You should now be in the emp_cursor cursor declaration.

Move your mouse over this icon to see the image

 

2.

Click Step Into . The Smart Data window shows a limited list of variables, namely those used in the line of code that is about to be executed, and in the previously executed line. Click the Data tab to see all the variables that are in scope.

Move your mouse over this icon to see the image

3.

Click Step Into twice more. You should now be about to execute the statement:
JavaSPResult := getHelloFromJava;

Move your mouse over this icon to see the image

Note: getHelloFromJava is the PL/SQL wrapper for the Java stored procedure you created earlier.

 

4.

Click Step Into . You should now be debugging the Java code for the Java stored procedure.

Move your mouse over this icon to see the image

Note: If you get a message about not being able to locate the source of the Java stored procedure, select the option to look in a project, and select Project from the list.

The Stack window shows the PL/SQL call stack and the Java call stack together.

Move your mouse over this icon to see the image

 

5.

Click Step Out to complete the Java stored procedure and return to the EMP_LIST procedure.

 

Modifying the PL/SQL Procedure at Runtime

Back to List

To modify the EMP_LIST procedure at runtime, as you would if you found an error while debugging, perform the following steps:

1.

Right-click the line that reads DBMS_OUTPUT.PUT_LINE(emp_tab(j).last_name); and choose Run to Cursor from the context menu.

Move your mouse over this icon to see the image

 

2.

Use the data window to drill into the PL/SQL table of records called emp_tab. In the data window you can access the entire structure of composite data types.

Keep drilling down until you see the values of the fields in a given record of the table.

Move your mouse over this icon to see the image

3.

Right click on the LAST_NAME field of the record and choose Modify Value from the context menu. Modify the last name to a name of your choice. Click OK.

Move your mouse over this icon to see the image

You've now modified the value in the PL/SQL table of records.

 

4.

Click Resume to allow the PL/SQL to run to completion. Check to see that your modified value is displayed in the Log window.

Move your mouse over this icon to see the image

 

Back to Topic List

In this lesson you used JDeveloper10g to accomplish the following:

Browsing database objects and table data

Defining a filter for browsing database objects

Creating and compiling a PL/SQL procedure

Executing and tuning a SQL statement

Creating and deploying a Java stored procedure

Debugging a PL/SQL procedure and a Java stored procedure

Back to Topic List

For more information, refer to the JDeveloper product page on OTN.

Move your mouse over this icon to hide all screenshots.