Java and JDBC for Oracle DBAs – Part 3: Git, Oracle schemas and your first Java application

Finally we have come to the point where we start to create some Java code. First we’ll install Git, the most widely used modern version control system. We’ll continue to download some code from GitHub to create our Oracle schemas, and then we’ll create a very simple – but our first – Java application. We’ll test compiling and running our code both from Eclipse and from Maven. Finally we’ll extend our application to use the JDBC driver and connect towards our database and our new database schemas.

Part 3: GitHub, Oracle Schemas and your first Java application

GitHub and example code

The JavaForOracleDBAs project

The code needed to follow this blog series, and the code that is generated throughout this series, can be found at the following GitHub project: https://github.com/lasjen/JavaForOracleDBAs. The repository will not be complete before the last blog post in the series is published.

Cloning the GitHub project

If you want to copy the files to your local computer, run something similar in your console (of course, make your own directory names):

$ cd /Users/lassejenssen
$ mkdir git-repo
$ cd git-repo
$ git clone git@github.com:lasjen/JavaForOracleDBAs.git
$ cd JavaForOracleDBAs

We’ll be using some of the SQL scripts found under the “oracle_schemas” directory in a second.

Creating Oracle Schemas for your test application

Too many Oracle applications use only one schema. The schema owning the data is also used accessing the data from the application. I strongly recommend NOT to do this in any production environment. To avoid this, I created a template for building the needed schemas for the Java developers in my department (when I worked in EVRY). A early version of this template (create_demo_users.sql and drop_demo_users.sql) is found under JavaForOracleDBAs/oracle_schemas (in the GitHub repository described above). A further description of the template can be found in one of my earlier blog posts.

Run the “create_demo_schema.sql” found under “JavaForOracleDBAs/oracle_schemas” as the SYSTEM user towards the database created in part 1. This will create a data owner (DEMODATA) and a application user (DEMO) used for accessing data from the application (both with password “demo”). The script also creates a package DEMO_GRANT with the procedure “grantToRoles”. This procedure grants the appropriate roles to the DEMO_RO and DEMO_RW roles, and therefor also to the DEMO user. Run this procedure after you have created any new tables under the DEMODATA schema. Later I’ll show how you can create a DDL trigger that will handle this automagically. You can run the “create_demo_schema.sql” from SqlPlus, or you can use another Oracle client (for instance SQL Developer):

$ sqlplus system@orcl
SQL> @create_demo_schema.sql
-- * ---------------------------------------------------------------------------- * --
-- * Your settings:                                                               * --
-- *     Oracle version:12                                                        * --
-- *     Plugable Name:ORCL                                                       * --
-- * ---------------------------------------------------------------------------- * --


-- * ---------------------------------------------------------------------------- * --
-- *                                                                              * --
-- * Script: create_dev_users.sql                                                 * --
-- *                                                                              * --
-- * Use:                                                                         * --
-- *   Run as SYSTEM (or SYSDBA if ATOMIKOS_ENABLE=Y)                             * --
-- *                                                                              * --
-- * Description: This script is potensially creating                             * --
-- *              users, roles, tablespaces and login triggers                    * --
-- *              for an test or development environment.                         * --
-- *                                                                              * --
-- * Author: Lasse Jenssen, mailto: lasse.jenssen@eritec.no                       * --
-- *                                                                              * --
-- * Note! Before running please set the required parameters                      * --
-- *       in the top of the script.                                              * --
-- *                                                                              * --
-- * ---------------------------------------------------------------------------- * --

*** --------------------------------------------- ***
***      Creating TABLESPACES ... (waiting)       ***
*** --------------------------------------------- ***
Creating tablespace demo_data succeeded.
Creating tablespace demo_idx succeeded.
Creating tablespace demo_lobs succeeded.

*** --------------------------------------------- ***
***     Creating roles ... (waiting)              ***
*** --------------------------------------------- ***
Creating role DEMO_RW succeeded.
Enabling Atomikos (grants) succeeded.
Creating role DEMO_RO succeeded.

*** --------------------------------------------- ***
***     Creating users ... (waiting)              ***
*** --------------------------------------------- ***
User DEMO created successfully.
User DEMO granted CREATE SESSION successfully
User DEMODATA created successfully.
User DEMODATA granted CREATE SESSION successfully
User DEMODATA granted owner rights successfully.
User DEMOSUPP created successfully.
User DEMOSUPP granted CREATE SESSION successfully
User DEMO granted DEMO_RW successfully.
User DEMOSUPP granted DEMO_RO successfully.

*** --------------------------------------------- ***
***     Creating trigger ... (waiting)            ***
*** --------------------------------------------- ***
Trigger SET_DEF_SCHEMA_DEMO created successfully.
Trigger SET_DEF_SCHEMA_DEMOSUPP created successfully.

*** --------------------------------------------- ***
***     Creating GRANT package ... (waiting)      ***
*** --------------------------------------------- ***
Package DEMO_GRANT created successfully.
Package body DEMO_GRANT created successfully.

If you want to clean up, and delete the schemas, roles, and the objects you just created, run the “drop_demo_schemas.sql” script. Now you are ready to start writing some Java code.

Your first Java Application

Finally we are ready to start creating our first Java project. We’ll be using both Eclipse and Maven for this. Open Eclipse. Go to the top menu, and click “File > New … > Project”: Your “New …” menu might not look 100% like mine (because I have installed a plugin, which we will get to later), but you will have the “Project …” choice. So don’t worry about the differences yet. Now we are going to use Maven to create our new project. Scroll-down to “Maven”, and chose “Maven Project”, and click “Next”:

Click “Browse …” and create a new directory next to where you cloned the GitHub repository above, and call it “JavaForOracleDBAsWS” (or something else you prefer). Choose this new directory as your workspace location, and then click “Next”:

In the “Catalog” field choose “Internal”, then choose the “maven-archetype-quickstart”, and click “Next”:

Now you are ready to give your project a group id and a project name (artifact id). When completed click “Finish”:

You should now have a project in Eclipse looking like this:

On the left side we see the “Package Explorer”, with 4 different files. The first file “App.java” is our application code. If we double click the “App.java” you’ll see the content on the right side in the code editor. As you this is a very simple application which will print “Hello World!” in the console when executed. The next file we’ll look at is the maven configuration file, pom.xml:

Note! You will find a text edition in GitHub. For a full description of the pom.xml file in Maven, go to https://maven.apache.org/guides/introduction/introduction-to-the-pom.html.

The pom.xml file is the the main configuration file in Maven. Here we set our dependencies, plugins or goals that can be executed, build profiles, and so on. Other information such as the project version, description, developers, mailing lists and such can also be specified.

If you look at the pom file above, you’ll recognize some of what we already seen. For instance you’ll recognize the groupId and artifactId, which we chose when we created the project. We also see that the project will be packaged into a Jar file. Last in the pom, we see the dependency towards the jUnit API, which is default in the quickstart archetype. This API is used in the test class which is called “AppTest.java”. The test in this class will be run in the test phase in maven. The default code includes one dummy test procedure – the “testApp” procedure:

// File: src/test/java/no/eritec/demo/AppTest.java
package no.eritec.demo.FirstApp;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class AppTest extends TestCase
{

    public AppTest( String testName )
    {
        super( testName );
    }

    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    public void testApp()
    {
        assertTrue( true );
    }
}

The pom.xml file inherits from the Super POM. For instance, information about the “src/main/java” and “src/main/resource” is default values gotten from the super pom. You can see your “effective pom” by double clicking the “pom.xml” file in Eclipse, and chose the “Effective POM” tab. You can also see this by running the “mvn” command in your console:

$ mvn help:effective-pom

The output is rather long, so I did not include this into this blog. Just run the command and see.

Build and execute with mvn command-line

Now we’ll see this in action when we compile our code in maven. I’ll first compile and package the code, and finally I’ll run the code through the maven command “mvn”. First I make sure I start of with a clean target directory by running “mvn clean”:

$ cd ../JavaForOracleDBAsWS/FirstApp/
$ ls -l
total 8
-rw-r--r--  1 lassejenssen  staff  754 Jul 18 10:47 pom.xml
drwxr-xr-x  4 lassejenssen  staff  128 Jul 18 10:47 src
drwxr-xr-x  3 lassejenssen  staff   96 Jul 18 12:54 target
$ mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< no.eritec.demo:FirstApp >-----------------------
[INFO] Building FirstApp 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ FirstApp ---
[INFO] Deleting /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.523 s
[INFO] Finished at: 2018-07-18T12:52:39+01:00
[INFO] ------------------------------------------------------------------------

Now we are ready to start compiling and packaging our new application. We could also do the clean in the same operation:

$ mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< no.eritec.demo:FirstApp >-----------------------
[INFO] Building FirstApp 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ FirstApp ---
[INFO] Deleting /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ FirstApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ FirstApp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ FirstApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ FirstApp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ FirstApp ---
[INFO] Surefire report directory: /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running no.eritec.demo.FirstApp.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ FirstApp ---
[INFO] Building jar: /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/target/FirstApp-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ FirstApp ---
[INFO] Installing /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/target/FirstApp-0.0.1-SNAPSHOT.jar to /Users/lassejenssen/.m2/repository/no/eritec/demo/FirstApp/0.0.1-SNAPSHOT/FirstApp-0.0.1-SNAPSHOT.jar
[INFO] Installing /Users/lassejenssen/git-repos/JavaForOracleDBAsWS/FirstApp/pom.xml to /Users/lassejenssen/.m2/repository/no/eritec/demo/FirstApp/0.0.1-SNAPSHOT/FirstApp-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.320 s
[INFO] Finished at: 2018-07-18T12:56:02+01:00
[INFO] ------------------------------------------------------------------------

If you follow the output you see the different phases which maven runs through (towards different areas of our project). For instance – maven both runs the “maven-compile-plugin” towards our main java class (App.java) and our test class (AppTest.java).

We also see how maven runs the test code, and finds and runs our test procedure successfully (no failures).

At the end we see that maven builds the jar file and installs it into the local maven repository (~/.m2 directory).

Now we are ready to run our first application. Go back to the console and run the following command:

$ mvn exec:java -Dexec.workingdir="target" -Dexec.mainClass="no.eritec.demo.FirstApp.App"
[INFO] Scanning for projects...
Downloading from maven.oracle.com: https://maven.oracle.com/org/codehaus/mojo/maven-metadata.xml
Downloading from maven.oracle.com: https://maven.oracle.com/org/apache/maven/plugins/maven-metadata.xml
Downloading from maven.oracle.com: https://maven.oracle.com/org/codehaus/mojo/exec-maven-plugin/maven-metadata.xml
[INFO]
[INFO] ----------------------< no.eritec.demo:FirstApp >-----------------------
[INFO] Building FirstApp 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ FirstApp ---
Hello World!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 14.507 s
[INFO] Finished at: 2018-07-18T13:04:44+01:00
[INFO] ------------------------------------------------------------------------

You could now try to go back to Eclipse and your “App.java” file. Edit the text in the output, and remember to save the file:

package no.eritec.demo.FirstApp;

public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello all Oracle DBAs!" );
    }
}

Then go back and re-execute the application.

$ mvn exec:java -Dexec.workingdir="target" -Dexec.mainClass="no.eritec.demo.FirstApp.App"
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< no.eritec.demo:FirstApp >-----------------------
[INFO] Building FirstApp 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ FirstApp ---
Hello all Oracle DBAs!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.887 s
[INFO] Finished at: 2018-07-18T13:07:43+01:00
[INFO] ------------------------------------------------------------------------

But why? We did not rebuild the application yet. This is because we changed the file in Eclipse, and Eclipse is automatically compiling and building while we are coding. If you close Eclipse, and edit the file in a simple text editor (such as “vim”), this would not happen. You would then first have to run “mvn install”, and then the “mvn exec:java ..:”.

Build and execute with Eclipse

We have already seen how Eclipse automatically compile and builds our project as we make changes. We can also run the application through Eclipse. Open the java file with the main procedure, and right click in the code editor (in the App.java file). Then choose “Run as …”, and choose “Java Application”. The code will now run, and the output will be shown in the console windows (see bottom of picture below):

We are now ready to start extending our pom.xml file, and introduce some new dependencies – the Oracle JDBC drivers. This will come in the part 4 of this blog series.

Post a Comment

Your email is never published nor shared. Required fields are marked *