97
JAVA AIN’T SCARY INTRODUCING JAVA TO PL/SQL PROGRAMMERS AMIS - 5 th April 2012

Java ain't scary - introducing Java to PL/SQL Developers

Embed Size (px)

DESCRIPTION

Many PL/SQL developers are a little scared of Java. They may have tried a little, but were driven off by J(2)EE architects and Java purists with terms like polymorphism and object oriented application design. This presentations tries to lower the threshold by introducing Java to PL/SQL developers by looking at the similarities. Both PL/SQL and Java are 3GL programming languages that a lot in common. Both are platform independent an run on a Virtual Machine (the Oracle Database in the case of PL/SQL). And even the OO specific characteristics of Java can be introduced using many familiar concepts.This presentation was held on 5th April 2012 at AMIS (Nieuwegein, The Netherlands) to a group of Java-fearing PL/SQL veterans. Most of them came out of the session feeling that they dared to take Java on now, having seen it demystified. Some even felt inspired to really start learning Java in anger.

Citation preview

Page 1: Java ain't scary - introducing Java to PL/SQL Developers

JAVA AIN’T SCARYINTRODUCING JAVA TO PL/SQL PROGRAMMERS

AMIS - 5th April 2012

Page 2: Java ain't scary - introducing Java to PL/SQL Developers

OVERVIEW

• Hello World!• Running Java on the JVM• Language basics: Methods, Variables &

simple Types• Debugging• Quiz• Dinner• Introduction to Java Objects• A little inheritance• Scratching the surface of

– Java to Database communication (JDBC)– Http to Java communication (Servlet)

Page 3: Java ain't scary - introducing Java to PL/SQL Developers

HELLO WORLD

• Create a PL/SQL program unit that writes Hello World! to the system output

• Create a Java program unit that writes Hello World! to the system output

procedure hello_worldisbegin dbms_output.put_line('Hello World!');end;

void hello_world()

{ System.out.println("Hello World!");}

Page 4: Java ain't scary - introducing Java to PL/SQL Developers

THE CONTEXT FOR THE HELLO_WORLD PROGRAM UNIT

• Create the PL/SQL Package that contains the hello_world program unit

• Create the Java Class that contains the helloWorld program unit

create or replace package welcome

procedure hello_world;

end welcome; -- end specification

create or replace package body welcome

procedure hello_worldisbegin dbms_output.put_line('Hello World!');end;

end welcome; -- end body

package nl.amis;

public class Welcome {

public void helloWorld(){ System.out.println("Hello World!");}

}

Page 5: Java ain't scary - introducing Java to PL/SQL Developers

HOW TO RUN THE HELLO_WORLD PROGRAM UNIT (PL/SQL)• In the context of a database connection,

invoke the procedure through the package specificationbegin welcome.hello_world;end;

Page 6: Java ain't scary - introducing Java to PL/SQL Developers

PL/SQL VM

(Oracle7, 1993)

PL/SQL VM

Page 7: Java ain't scary - introducing Java to PL/SQL Developers

PL/SQL VIRTUAL MACHINE

• Ever since Oracle7, the Oracle RDBMS contains a PL/SQL Virtual Machine

• That means: write [PL/SQL] once, run anywhere (as long as the RDBMS is running)

• This portability of PL/SQL across platforms is pretty extraordinary!

PL/SQL

Page 8: Java ain't scary - introducing Java to PL/SQL Developers

JAVA VIRTUAL MACHINE (JVM)

• Java is executed by the JVM (Java Virtual Machine)

• On almost any platform, a platform specific JVM is available

• Java is written once, then executed unchanged on the JVM on the target platform

• ‘write once, run anywhere’ was the tagline for Java Java

Page 9: Java ain't scary - introducing Java to PL/SQL Developers

HOW TO RUN THE HELLOWORLD PROGRAM UNIT (JAVA)• Start JVM and instruct it to run a Java Class

– More specifically: to invoke the main method of the designated Java Class: java nl.amis.Welcome

• In JDeveloper: CTRL + F11

package nl.amis;

public class Welcome { public static void helloWorld() { System.out.println("Hello World!"); } public static void main(String[] args) { Welcome.helloWorld(); }}

Page 10: Java ain't scary - introducing Java to PL/SQL Developers

RUNNING HELLO_WORLD

• Connect to PLSQL VM (i.e. the database) and execute anonymous PL/SQL block

• Start JVM and execute main method

begin welcome.hello_world;end;

... public static void main(String[] args) { Welcome.helloWorld();}...

Page 11: Java ain't scary - introducing Java to PL/SQL Developers

ABOUT THE JVM

• Java is compiled at design time into byte code – held in .class files (one .class per .java file)

• The platform specific JVM loads class files (from .class or from JAR

• Note: byte code (classes) can be created in other ways too besides from Java code– For example from Groovy, JRuby, BeanShell,

Jython and various other languages– The JVM is not correctly named!

Page 12: Java ain't scary - introducing Java to PL/SQL Developers

ABOUT THE JVM (2)

• Byte code is not machine language: the platform independent byte code is interpreted in the target JVM and turned into platform specific actions

• Note: Byte code (‘class files’) can be decompiled

• Note: there is no ‘dynamic Java’ such as execute immediate ‘Java fragment’

Page 13: Java ain't scary - introducing Java to PL/SQL Developers

HABITAT OF THE JVM

Page 14: Java ain't scary - introducing Java to PL/SQL Developers

CLASS

• Program Unit for Java– Similar to PL/SQL package

• Class with Main method can be executed– Other classes and methods only invoked from

within Java code• Execute means: having JVM load, instantiate

& invoke• In JDeveloper, run means

– Compile Java code (.java) into byte code (.class)– Call Java run time (JVM) with instruction to

execute class• Which in turn means: invoke main method of the

class

Page 15: Java ain't scary - introducing Java to PL/SQL Developers

METHODS

• Functions are called methods• A method that does not return a

value (a procedure in PL/SQL terms) is defined with void as return type:

• Methods can be public, protected, default or private– Determining accessibility from outside class and

from outside package (similar to PL/SQL’s package specification and body)

public void helloWorld() { System.out.println("Hello World!");}

Page 16: Java ain't scary - introducing Java to PL/SQL Developers

SOME LINGO AND OTHERJAVA TID BITS• Java is case sensitive• It is common practice to use

‘camel case’ for naming classes, methods and variables (and not underscores)

• { and } are used to indicate the start and end of code segments (where PL/SQL uses begin and end)– Such as methods, nested blocks in if, else, loops

etc.– {} can be empty (similar to PL/SQL: begin null;

end;)• Note: the indentation is not meaningful to the

Java compiler – only to the human eye

public void helloWorld() { System.out.println("Hello World!"); { }}

Page 17: Java ain't scary - introducing Java to PL/SQL Developers

SOME STRIKING – AND UNIMPORTANT – DISTINCTIONS BETWEEN JAVA AND PL/SQL

• Java

l_name varchar2(20):= 'John'; -- nice name is it not?begin if l_name = 'Hank' then l_name:= l_name || 'B.'; end if;end;

{ // what wonderful name this is String name = "John"; if (name == "Hank") { name = name + "B."; }}

PL/SQL Java

Assignment := =

Equality = ==

String concatenation || +

String quoting ' "

IF construct if then [else ] end if if () {} [else {}]

Logical operators AND , OR, NOT &&, ||, !

Comment -- and /* … */ // and /* … */

Page 18: Java ain't scary - introducing Java to PL/SQL Developers

VARIABLES

• Global – defined (anywhere) at class level– accessible from any method– class level variables can be public – meaning they

are accessible from outside the class• Local – defined (anywhere) inside a method

– only accessible within the method

package nl.amis;

public class Welcome { private String lastName = "Doe"; public String greeting = "Hello"; public static void helloWorld() { String firstName = "John"; System.out.println(greeting + firstName + lastName); } }

Page 19: Java ain't scary - introducing Java to PL/SQL Developers

VARIABLES

• Definition of a variable is reversed compared to PL/SQL: – first the type then the name

• variables are not constrained through their definition (such as VARCHAR2(250) in PL/SQL)

• some native types have built-in limitations: byte, short, integer, long, float, double, booleanpackage nl.amis;

public class Welcome { byte smallNumber = 127; short notThatShort = 32767; // 16 bits int substantialNumber = 2147483647; // 32 bits long potentiallyLargeNumber = 0; // 64 bits, 9,2 trillion

// floating point values: float fractured = 0.1f; // single-precision 32-bit, e+38 double verySmallAndVeryLarge = -0.1; // 64 bits, e+308 boolean itsNotALie = false;}

Page 20: Java ain't scary - introducing Java to PL/SQL Developers

PRINT THE FACTORIALS FOR 1..10

PL/SQL

create or replacepackage factorialsas

procedure main (p_upper in number);

end factorials;

create or replace package body factorialsas function factorial(p_i in number) return number is begin if (p_i<2) then return 1; else return p_i * factorial(p_i-1); end if; end factorial; procedure printFactorials(p_upper in number) is begin for i in 0..p_upper loop dbms_output.put_line(i || '! = ' || factorial(i)); end loop; end printFactorials;

procedure main(p_upper in number) is begin Factorials.printFactorials(10); end main;end factorials;

begin factorials.main(10);end;

Page 21: Java ain't scary - introducing Java to PL/SQL Developers

PRINT THE FACTORIALS FOR 1..10

Java

public class Factorials { private static int factorial(int i) { if (i<2) return 1; else return i * factorial(i-1); } private static void printFactorials( int upper) { for (int i=0; i<upper; i++) { System.out.println ( i + "! = " + factorial(i)); } } public static void main(String[] args) { Factorials.printFactorials(10); }

}

java.exe -classpath C:\JavaAintScary\classes

nl.amis.Factorials

Page 22: Java ain't scary - introducing Java to PL/SQL Developers

PRINT THE FACTORIALS FOR 1..10PL/SQL Java

public class Factorials { private static int factorial(int i) { if (i<2) return 1; else return i * factorial(i-1); }

private static void printFactorials ( int upper) { for (int i=0; i<upper; i++) { System.out.println ( i + "! = " + factorial(i)); } }

public static void main(String[] args) { Factorials.printFactorials(10);} }

create package body factorials as

function factorial(p_i in number) return number is begin if (p_i<2) then return 1; else return p_i * factorial(p_i-1); end if; end factorial; procedure printFactorials (p_upper in number) is begin for i in 0..p_upper loop dbms_output.put_line(i || '! = ' || factorial(i)); end loop; end printFactorials;

procedure main(p_upper in number) is begin Factorials.printFactorials(10); end main;end factorials;

Page 23: Java ain't scary - introducing Java to PL/SQL Developers

DEBUGGING JAVA IN JDEVELOPER

• Java code running in a JVM can be remote debugged

• That means for example that JDeveloper can listen in to the execution of Java classes and methods– Pausing at breakpoints– Inspecting objects and variables– Inspecting the call stack– Manipulating values– Changing code ‘on the fly’

Page 24: Java ain't scary - introducing Java to PL/SQL Developers

DEBUGGING IN ACTION

Page 25: Java ain't scary - introducing Java to PL/SQL Developers

SOME LOOPING CONSTRUCTSPL/SQL Java

{ int i = 0; int f = 1;

for (; ; ) { // alternative // while (i<10) do { System.out.println(i + "! = " + f); if (i == 9) break; // not needed // when using the while loop i++; if (i == 1) continue;

f = f * i; } //for}

declare i number := 0; f number := 1;begin loop -- alternative: -- while i < 10 loop dbms_output.put_line (i || '! = '|| f); exit when i = 9; -- not needed -- when using the while loop i:= i+ 1; if i=1 then continue; -- 11g command end if; f:= f * i; end loop;end;

Page 26: Java ain't scary - introducing Java to PL/SQL Developers

SOME LOOPING CONSTRUCTSPL/SQL Java

{ for (int i = 10; i>1 ; i=i-2) { System.out.println(i); }}

declare step number := 2;begin -- print numbers 10, 8, 6, 4, 2 for i in reverse 1..5 loop -- STEP does not exist in PL/SQL -- for i in reverse 1..5 step 2 loop dbms_output.put_line(i*step ); end loop;end;

Page 27: Java ain't scary - introducing Java to PL/SQL Developers

OTHER LANGUAGE CONSTRUCTSPL/SQL Java

private static float divide( int a,int b) { try { return a/b; } catch (ArithmeticException ae) { System.out.println(ae.getMessage()); throw ae; } }

public static void division() { int a = 6, b = 0; try { System.out.println("result of division: " + divide(a, b)); } catch (Exception e) { System.out.println("Some exception was returned!"); }}

function divide( p_a in number , p_b in number) return number is BEGIN return p_a / p_b; EXCEPTION WHEN ZERO_DIVIDE THEN dbms_output.put_line ('Trying to divide by zero'); raise; END;DECLARE l_a NUMBER := 6; l_b NUMBER := 0; begin dbms_output.put_line(' result of division: ' || divide(l_a, l_b));exception when others then dbms_output.put_line (' Some exception was returned!');end;

Page 28: Java ain't scary - introducing Java to PL/SQL Developers

DECODE…

• PL/SQL • Java

declare l_gender varchar2(1):= 'F';begin dbms_output.put_line ( decode( l_gender , 'F','FEMALE' ,'MALE' ) );end;

// using a ternary expression...{ String gender ="F"; System.out.println ( gender=="F" ? "FEMALE" : "MALE" );}...

declare l_gender varchar2(1):= 'F';begin dbms_output.put_line ( case l_gender when 'F' then 'FEMALE' else 'MALE' end );end;

X

Page 29: Java ain't scary - introducing Java to PL/SQL Developers

THAT BIG THING ABOUT JAVA…

Objects….

Page 30: Java ain't scary - introducing Java to PL/SQL Developers

THE PERSON CLASS:“MOTHER OF MANY OBJECTS”

public class Person { private String firstName; private String lastName; private int salary; private String gender;

public String displayLabel() { return (gender=="M" ? "Mr." : "Mrs.") + firstName + " " + lastName; }

}

Page 31: Java ain't scary - introducing Java to PL/SQL Developers

QUIZ TIME

• What is the meaning of the acronym ‘JVM’

• What is meant by ‘write once, run anywhere’?

• In which environments can you run Java?

• How do you get from a .java file to a running program doing things?

Page 32: Java ain't scary - introducing Java to PL/SQL Developers

QUIZ TIME

• What is wrong with this Java statement?

string label_value = 'John' + 'Doe ' ; -- assign name

Page 33: Java ain't scary - introducing Java to PL/SQL Developers

QUIZ TIME

• What is the PL/SQL equivalent of this Java snippet?{ int i = 0; for (; ; ) { System.out.println(i++); if (i == 9) break; }}

declare i number := 0;begin loop dbms_output.put_line(i); i:= i+ 1; exit when i == 9; end loop;end;

declare i number := 0;begin loop dbms_output.put_line(i); i:= i+ 1; if i = 9 then break; end loop;end;

declare i integer := 0;begin loop dbms_output.put_line(i); i:= i+ 1; exit when i = 9; end loop;end;

Page 34: Java ain't scary - introducing Java to PL/SQL Developers

QUIZ TIME

• What is wrong with this Java statement?

{ for (int i = 10; i>1 ; i=i--) { System.Out.println(i); }}

Page 35: Java ain't scary - introducing Java to PL/SQL Developers

QUIZ TIME

• What is the output from running this Java statement?package nl.amis;

public class DoIt { private String lastName = "Obama"; public String greeting = "Hello"; public static void main( String[] args) { String firstName = "Michelle"; System.out.println(greeting + "Mrs." + firstName); } }

java.exe -classpath C:\JavaAintScary\classes

nl.amis.DoIt

Page 36: Java ain't scary - introducing Java to PL/SQL Developers

DINNER

Page 37: Java ain't scary - introducing Java to PL/SQL Developers

JAVA OBJECTS

Page 38: Java ain't scary - introducing Java to PL/SQL Developers

create or replace package thing asprocedure set_value(p_value in varchar2);

function get_value return varchar2;

end thing;

create or replace package body thingasg_value varchar2(100):= 'VALUE';

procedure set_value(p_value in varchar2) isbegin g_value := p_value;end set_value;

function get_value return varchar2 isbegin return g_value;end get_value;

begin g_value:= 'initialized value';end thing;

begin dbms_output.put_line ('value = '||thing.get_value);end;

begin thing.set_value('hello world'); dbms_output.put_line ('value = '||thing.get_value);end;

begin dbms_output.put_line ('value = '||thing.get_value);end;

Page 39: Java ain't scary - introducing Java to PL/SQL Developers

Package THINGget_valueset_value

Database Session 1 Database Session 2

Page 40: Java ain't scary - introducing Java to PL/SQL Developers

SEPARATION OF (SHARED) CODE AND INSTANCE DATA

Package THINGget_valueset_value

Database Session 1

Database Session 2

SHARED MEMORY

PER SESSION MEMORY

UGASession 1

THING.g_value[Hello World]

Database Session 3

UGASession 2

THING.g_value[Goodbye World]

UGASession 3

THING.g_value[initialized value]

Page 41: Java ain't scary - introducing Java to PL/SQL Developers

PACKAGE AND MULTIPLE USER SESSIONS• Package state is kept in UGA

– Different sessions have different state for package globals

– Note: with dbms_session.reset_package, all packages in the sessions are ‘de-instantiated’

• Global variable is not really global– it means ‘retained across multiple calls in the same

user session’ – not across sessions– Note: true global values can be achieved using

Globally Accessible Application Context• When a package is first called in a session, its

initialization section is executed– And global variables assume default values– The package is ‘instantiated within the session’: the

UGA starts to hold values for the globals• Question: what is global about a GLOBAL

TEMPORARY TABLE?

Page 42: Java ain't scary - introducing Java to PL/SQL Developers

THING IN JAVAcreate or replace package thing asprocedure set_value(p_value in varchar2);

function get_value return varchar2;

end thing;

create or replace package body thingasg_value varchar2(100):= 'VALUE';

procedure set_value(p_value in varchar2) isbegin g_value := p_value;end set_value;

function get_value return varchar2 isbegin return g_value;end get_value;

begin g_value:= 'initialized value';end thing;

public class Thing {

public void setValue(String value) { this.value = value; }

public String getValue() { return value; } String value = "VALUE";

public Thing() { value = "initialized value"; }}

Page 43: Java ain't scary - introducing Java to PL/SQL Developers

create or replace package thing asprocedure set_value(p_value in varchar2);

function get_value return varchar2;

end thing;

public class Thing {

public void setValue(String value) { this.value = value; }

public String getValue() { return value; } String value = "VALUE"; public Thing() { value = "initialized value"; } public static void main(String[] args) { Thing thing = new Thing(); System.out.println ("value = "+ thing.getValue()); thing.setValue("Hello World"); System.out.println ("value = "+ thing.getValue()); }

}

begin dbms_output.put_line ('value = '||thing.get_value); thing.set_value('hello world'); dbms_output.put_line ('value = '||thing.get_value);end;

Page 44: Java ain't scary - introducing Java to PL/SQL Developers

MULTIPLE THING INSTANCES WITH EACH ITS INSTANCE DATA

public class Thing {

public void setValue(String value) { this.value = value; }

public String getValue() { return value; } String value = "VALUE"; public Thing() { value = "initialized value"; }

}

public class ThingRunner { public static void main(String[] args) { Thing thing = new Thing(); System.out.println ("value = "+ thing.getValue()); thing.setValue("Hello World"); System.out.println ("value = "+ thing.getValue()); Thing thing2 = new Thing(); System.out.println ("value (2) = "+ thing2.getValue()); thing2.setValue("Goodbye World"); System.out.println ("value (2) = "+ thing2.getValue()); System.out.println ("value = "+ thing.getValue()); }

}

Page 45: Java ain't scary - introducing Java to PL/SQL Developers

SEPARATION OF (SHARED) CODE AND INSTANCE DATA

Class THINGgetValuesetValue

SHARED

INSTANCES

thing value

[Hello World]

thing 2value

[Goodbye World]

Page 46: Java ain't scary - introducing Java to PL/SQL Developers

CLASS AND OBJECTS

• A class is like a PL/SQL package: the template for an instance– At run time, the class is instantiated before its

methods can be executed• An instantiated class is called:…. an object

– During instantiation: members (global variables) are instantiated and initialization code can be executed• The Constructor method

• Note: this also applies to objects in the Oracle Database:– Create type as object ….

Class THINGgetValuesetValue

Object thingvalue

Object thing2value

Object thing3value

Object thing4value

Page 47: Java ain't scary - introducing Java to PL/SQL Developers

TRUE GLOBAL IN JAVA

• Truly Global means: shared between all instances of a class in a JVM

• Anything in Java designated ‘static’ is truly global or shared between all objects based on the same class

Class THINGstatic value

SHARED

INSTANCES

thing value

thing 2value

Page 48: Java ain't scary - introducing Java to PL/SQL Developers

TRUE GLOBAL IN JAVA

public class Thing {

static String value = "VALUE";

public void setValue(String value) { this.value = value; }

public String getValue() { return value; }

public Thing() { value = "initialized value"; }}

Object thingvalue

Object thing2value

Class THINGstatic value

Page 49: Java ain't scary - introducing Java to PL/SQL Developers

INSTANTIATING A PERSON (OBJECT)public class Person {

private String firstName; private String lastName; private int salary; private String gender;

public String displayLabel() { return (gender=="M" ? "Mr." : "Mrs." ) + firstName + " " + lastName; }

}

public static void main(String[] args) { Person p = new Person(); System.out.println(p.displayLabel());}

Page 50: Java ain't scary - introducing Java to PL/SQL Developers

INSTANTIATING A PERSON AND SETTING PERSONAL PROPERTIES

public class Person { private String firstName; private String lastName; private int salary; private String gender;

public void setFirstName (String firstName) { this.firstName = firstName; }

public String getFirstName() { return firstName; }

public void setLastName(String lastName) ...// getters and setters for all properties

public String displayLabel() { return (gender=="M" ? "Mr." : "Mrs." ) + firstName + " " + lastName; } }

public static void main(String[] args) { Person p = new Person(); p.setFirstName("John"); p.setLastName("Doe"); p.setGender("M"); System.out.println(p.displayLabel());}

Page 51: Java ain't scary - introducing Java to PL/SQL Developers

PASSING A PERSON TO A METHOD

package nl.amis;

public class PersonalAssistant { public static void printPersonalLabel ( Person person) { System.out.println ( (person.getGender()=="M" ? "Mr." : "Mrs.") + person.getFirstName() + " " + person.getLastName() ); }}

public static void main(String[] args) { Person p = new Person(); p.setFirstName("John"); p.setLastName("Doe"); p.setGender("M"); PersonalAssistant.printPersonalLabel(p);}

Page 52: Java ain't scary - introducing Java to PL/SQL Developers

NOTES ON STATIC METHODS

• Methods can be designated static too• Static methods can only access static class

members (that means: variables that are also static in the Class)

• A static method can be invoked on the Class – you do not first need to instantiate an object

vs.

public static void main(String[] args) { ... PersonalAssistant.printPersonalLabel(p);}

public static void main(String[] args) { ... PersonalAssistant pa = new PersonalAssistant(); pa.printPersonalLabel(p);}

Page 53: Java ain't scary - introducing Java to PL/SQL Developers

MULTIPLE PEOPLE

public static void main(String[] args) { Person p = new Person(); p.setFirstName("John"); p.setLastName("Doe"); p.setGender("M"); Person p2 = new Person(); p2.setFirstName("Jane"); p2.setLastName("Doe"); p2.setGender("F"); System.out.println(p.displayLabel()); System.out.println(p2.displayLabel());}

Person pfirstName JohnlastName DoeGender M

Person p2firstName JanelastName DoeGender F

Class Person…

displayLabel

Page 54: Java ain't scary - introducing Java to PL/SQL Developers

TWO TYPES OF VARIABLES

• Variables can contain a value such as a number or boolean– Primitive types: byte, short, integer, long, float,

double, boolean• Variables can also contain a reference to an

object– Built-in Classes such as Byte, Short, Integer,

Long, Float, Double, Boolean, Date– Custom classes such as Person and Thing

• String is a special beast: it is an object reference but has also some primitive behavior – For example: create String with simple

assignment, without new to instantiate a new String

... String value = "VALUE"; public Thing() { value = "initialized value"; }

Page 55: Java ain't scary - introducing Java to PL/SQL Developers

METHODS ON THE BUILT-IN STRING CLASS• Methods on a String

Page 56: Java ain't scary - introducing Java to PL/SQL Developers

METHOD CHAINING

• Using various methods on String

• When a method returns an object, a method can be invoked on that object – and when that method also returns an object ..

String someString = "Hello";someString = someString.concat(" World "). replaceAll("Hello", " Goodbye").toUpperCase().trim();System.out.println(someString);

String someString = "Hello";someString = someString.concat(" World ");someString = someString.replaceAll("Hello", " Goodbye");someString = someString.toUpperCase();someString = someString.trim();System.out.println(someString);

Page 57: Java ain't scary - introducing Java to PL/SQL Developers

PRIMITIVE VARIABLES AND PARAMETERS• Primitives are just a value

– Assigning one variable to another leads to copying the value

• Passing a primitive variable as parameter to a method means passing a copy of the value

– Primitive parameters are read-only – there is no equivalent to in out or out parameters

1.2312FALSE255

255

25559182

Page 58: Java ain't scary - introducing Java to PL/SQL Developers

OBJECT VARIABLES AND PARAMETERS• Object variables are references to objects

– Multiple references to the same object can exist

– When no references exist any longer, the object will be garbage collected (eventually)

• Passing an object variable as parameter means passing a read-only copy of the object reference– The object itself is editable!

Person

Person

<pointer>

<pointer>

<pointer>

<pointer>

Page 59: Java ain't scary - introducing Java to PL/SQL Developers

PERSONAL DETAILS

• There is more to a Person than a few simple properties

• Person properties can be– References to other objects (such as a social

profile)– Collections of values or object references (such

as email addresses)

Person

Social Profile

Email Address[es]

Page 60: Java ain't scary - introducing Java to PL/SQL Developers

INTRODUCING CLASS SOCIALPROFILE

Person

Social Profile

Email Address[es]

Page 61: Java ain't scary - introducing Java to PL/SQL Developers

INTRODUCING CLASS EMAILADDRESS

Person

Social Profile

Email Address[es]

Page 62: Java ain't scary - introducing Java to PL/SQL Developers

PERSON WITH HIS DETAILS

Person

Social Profile

Email Address[es]

Page 63: Java ain't scary - introducing Java to PL/SQL Developers

CREATING A COMPLEX PERSONPerson p = new Person("John", "Doe", 4500, "M");p.getSocialProfile().setBlog("http://johndoe.blogspot.com");p.getSocialProfile().setMsn("JohnnyDoe_234");p.getEmailAddresses().add(new EmailAddress("[email protected]","P"));p.getEmailAddresses().add(new EmailAddress("[email protected]","W"));

Person

Social Profile

Email Address[es]

Page 64: Java ain't scary - introducing Java to PL/SQL Developers

QUICK COLLECTION OVERVIEW AND COMPARISON

declare type string_tbl_t is table of varchar2(200); l_names string_tbl_t:= string_tbl_t(); l_index number;begin l_names.extend(); l_names(1):= 'Tobias'; l_names.extend(); l_names(l_names.last):= 'Lex'; l_index:= l_names.first; loop exit when l_index is null; dbms_output.put_line (' Name '||l_index||' : ' ||l_names(l_index) ); l_index := l_names.next(l_index); end loop; end;

... List<String> names = new ArrayList<String>(); names.add("Tobias"); names.add("Lex"); int index = 1; for (String name:names) { System.out.println ("Name "+index+++" : "+name); }//for

}

Page 65: Java ain't scary - introducing Java to PL/SQL Developers

PERSONAL DETAILS

Person

Employee Customer

Social Profile

Email Address[es]

Page 66: Java ain't scary - introducing Java to PL/SQL Developers

ENTITY RELATIONSHIP MODELING

PERSON

EMPLOYEE

CUSTOMER

EMAIL_ADDRESS

SOCIAL_PROFILE

Page 67: Java ain't scary - introducing Java to PL/SQL Developers

OBJECT ORIENTED DESIGN

PERSON

EMPLOYEE CUSTOMER

EMAIL_ADDRESS

SOCIAL_PROFILE1

0..*1

0..1

Page 68: Java ain't scary - introducing Java to PL/SQL Developers

CODE FOR SUB CLASSES

public class Employee extends Person { private String job; private int departmentId; private Date hiredate;

// getters and setters }

public class Customer extends Person { private String companyName; private String telephoneNumber;

// getters and setters }

Page 69: Java ain't scary - introducing Java to PL/SQL Developers

PERSONAL ASSISTANT: CAN IT DEAL WITH EMPLOYEES AND CUSTOMERS?package nl.amis;

public class PersonalAssistant { public static void printPersonalLabel ( Person person) { System.out.println ( (person.getGender()=="M" ? "Mr." : "Mrs.") + person.getFirstName() + " " + person.getLastName() ); }} public static void main(String[] args) {

Employee e = new Employee(); e.setFirstName("John"); e.setLastName("Doe"); e.setGender("M"); e.setJob("Manager"); PersonalAssistant.printPersonalLabel(e);}

?

Page 70: Java ain't scary - introducing Java to PL/SQL Developers

AN INSTANCE OF A SUB CLASS IS ALSO AN INSTANCE OF ITS SUPERCLASS(ES)

• Of course each Employee and every Customer is also a Person!

• A method that accepts the superclass as input, will be able to process instances of the subclass just fine– Ask for Person, and get Customer or Employee

is OK• Note: the reverse is not true: when the

required input is a specialized sub type, then a supertype instance is not good enough– Ask for Customer and get a Person is NOT OK

public static void printEmployeeLabel ( Employee employee) { System.out.println ( employee.getJob() + " in department " + employee.getDepartmentId() ); }

Person p = new Person(); p.setFirstName("John"); p.setLastName("Doe"); p.setGender("M"); PersonalAssistant.printEmployeeLabel(p);

Page 71: Java ain't scary - introducing Java to PL/SQL Developers

ANY METHOD & PROPERTY DEFINED ON THE SUPERCLASS ALSO EXISTS FOR A SUBCLASS

• Properties and methods on Person class are inherited by the subclasses Employee and Customer

public class Employee extends Person { private String job; private int departmentId; private Date hiredate;

// getters and setters }

Employee e = new Employee();e.setFirstName("John");e.setLastName("Doe");e.setGender("M");e.setJob("Manager");e.setDepartmentId(10);

public class Person { private String firstName; private String lastName; private int salary; private String gender; ...

Page 72: Java ain't scary - introducing Java to PL/SQL Developers

OVERRIDING METHODS IN THE SUBCLASS – PROVIDING A SPECIALIZED IMPLEMENTATION

• Methods can be overridden in a sub class– the sub class has its own version of the method

with the exact same signature– invoking the method on an instance of the sub

class results in execution of the specialized implementation

– note: the sub class implementation can invoke the super class method too

public class Person { ... public String displayLabel() { return (gender=="M" ? "Mr." : "Mrs." ) + firstName + " " + lastName; } }

public class Employee extends Person { ... public String displayLabel() { return super.displayLabel() + " (" + this.job+")"; }

Person

displayLabel()

Employee

displayLabel()

Page 73: Java ain't scary - introducing Java to PL/SQL Developers

PRINTING THE EMPLOYEE DISPLAYLABEL• The Employee displayLabel method is both

– the Employee’s special (overridden) implementation

– as well as the super’s (Person’s) original version

Employee e = new Employee();e.setFirstName("John");e.setLastName("Doe");e.setGender("M");e.setJob("Manager");e.setDepartmentId(10);System.out.println( e.displayLabel());

Person

displayLabel()

Employee

displayLabel()

Page 74: Java ain't scary - introducing Java to PL/SQL Developers

IMPERSONATING AN EMPLOYEE?

• When a method accepts a handle to a Person object

• and it receives a handle to a specialized type of Person – an Employee (no less)

• it will invoke the specialized, overridden method

public String personalLabel(Person p) { return p.displayLabel();}

Employee e = new Employee();e.setFirstName("John");e.setLastName("Doe");e.setGender("M");e.setJob("Manager");e.setDepartmentId(10);System.out.println( personalLabel());

Page 75: Java ain't scary - introducing Java to PL/SQL Developers

EMPLOYING A PERSON?

• When a method accepts a handle to a Person object

• it can determine if the Person is just a Person or someone more special…

public String inspectPerson(Person p) {}

public String inspectPerson(Person p) { if (p instanceof Employee) { return "Employee"; } else if (p instanceof Customer) { return "Customer"; } else { return "Person"; }}

Page 76: Java ain't scary - introducing Java to PL/SQL Developers

CASTING A PERSON IN THE ROLE OF EMPLOYEE• When a method accepts a handle to a Person

object

• and it has determined that the Person is someone more special – an Employee – it can also address the Employee capabilities of the Person object

public String inspectPerson(Person p) {}

public static void printSpecialPersonalLabel ( Person person) { String label = (person.getGender()=="M" ? "Mr." : "Mrs.") + person.getFirstName() + " " + person.getLastName();

if (person instanceof Employee) { label = label + " ("+ ((Employee)person).getJob()+")"; }

if (person instanceof Customer) { label = label + " ("+ ((Customer)person).getCompanyName()+")"; } System.out.println(label); }

Page 77: Java ain't scary - introducing Java to PL/SQL Developers

CASTING IS SIMILAR TO CONVERSION IN PL/SQL• PL/SQL has explicit (to_number, to_char) and

implicit conversion – similar to casting in Java

• The keyword cast is also explicitly used in PL/SQL

declare i varchar2(10) := '21'; function add( p1 in number, p2 in varchar2) return number is begin return p1 + p2; end add;

begin dbms_output.put_line(add(i,21));end;

declare l_timestamp TIMESTAMP := cast ('05-Apr-2012 09.00.00.00 PM ' as TIMESTAMP ); l_number number(2) := cast ('21' as number); l_names string_table;begin select cast ( multiset(select ename from emp) as string_table) into l_names from dual;

Page 78: Java ain't scary - introducing Java to PL/SQL Developers

TECHNICAL OBJECT HIERARCHY

• For example: RichTable class from ADF Faces:

Page 79: Java ain't scary - introducing Java to PL/SQL Developers

DESIGN BY CONTRACT

• A contract is specification of the functionality that is (or will be) provided by some implementation– Without stipulating details about how the

implementation is done– And sometimes well before the implementation

is done• For consumers the contract is enough to

create the software that relies on the functionalitycreate or replacepackage calculatoras

function add( p1 in number, p2 in number)return number;

function multiply( p1 in number, p2 in number)return number;

end calculator;

Page 80: Java ain't scary - introducing Java to PL/SQL Developers

DESIGN BY CONTRACT IN JAVAINTRODUCING THE JAVA INTERFACE• The contract dictating functionality in Java is

called an Interface– It defines methods – without providing

implementations for those methods

• Classes can implement no, one or multiple Interfaces– And extend from only one super-class

• Any interface can be implemented by multiple classes

package nl.amis

public interface Calculator {

public int add( int p1, int p2);

public int multiply(int p1, int p2);

}

Page 81: Java ain't scary - introducing Java to PL/SQL Developers

CODING TO THE INTERFACE – INVOKING THE INTERFACE WITHOUT IMPLEMENTATION

• Classes can invoke the ‘interface’ without knowledge about the actual classes that implement the contractpublic class Worker { private Calculator calculator; // instance of the interface public void tableOfMultiplication( int table) { for (int i=1;i<=10;i++) { System.out.println( i +" * "+ table + " = " + calculator.multiply(i, table)); }} public void setCalculator(Calculator calculator) { this.calculator = calculator;}

public static void main(String[] args) { Worker worker = new Worker(); worker.setCalculator(new SpecialCalculator()); worker.tableOfMultiplication(5);}}

Calculator

Page 82: Java ain't scary - introducing Java to PL/SQL Developers

IMPLEMENTING THE INTERFACE

• Any class can implement an interface (or more than one) if it publishes the required methodspackage nl.amis;

public class SpecialCalculator extends Object implements Calculator , SecondContract { public int add(int p1, int p2) { return p1 + p2; }

public int multiply(int p1, int p2) { return p1 * p2; }

// defined in interface SecondContract public String remove(String s1, String s2) { return s1.replaceAll(s2, ""); } }}

Page 83: Java ain't scary - introducing Java to PL/SQL Developers

LEVERAGE METHODS FROM OTHER INTERFACES AS WELL• Testing if an object implements an interface

is done using instanceof• Invoking methods from an interface on an

object can be done by casting the object to the interface

public class Worker { public static void main(String[] args) { Calculator calculator = new SpecialCalculator(); if (worker.calculator instanceof SecondContract) { System.out.println(((SecondContract)calculator).remove ("HELLO WORLD", "O")); }//if}}

Page 84: Java ain't scary - introducing Java to PL/SQL Developers

OVERVIEW

• Hello World!• Running Java on the JVM• Language basics: Methods, Variables &

simple Types• Debugging• Quiz• Dinner• Introduction to Java Objects• A little inheritance• Scratching the surface of

– Java to Database communication (JDBC)– Http to Java communication (Servlet)

Page 85: Java ain't scary - introducing Java to PL/SQL Developers

Plain JDBC Ibatis, Spring JPA (Hibernate) EJB (CMP) WS*

JDBC

RDBMS

“NO SQL”

Cache

Data Grid

JAVA APPLICATIONS & DATABASE

Page 86: Java ain't scary - introducing Java to PL/SQL Developers

JDBC – JAVA DATABASE CONNECTIVITY• Using a JDBC Driver…• Any Java program can create a connection to

almost any relational database– Connecting to a schema using a password, just

like Forms, SQL*Plus or an APEX browser session– Note: most databases have their own, special

JDBC drivers• Through that connection, the Java program

can query, do DML and invoke Stored Procedures and Functions

• Java programs can handle long running transactions and sessions

Page 87: Java ain't scary - introducing Java to PL/SQL Developers

QUERY EMPLOYEE DETAILS

• Execute SQL Query via JDBC – process ResultSet:

public static void main(String[] args) throws SQLException { Connection connection = ConnectionManager.getConnection(); // Get a statement from the connection Statement stmt = connection.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery("SELECT empno,ename, sal FROM emp"); // Loop through the result set while (rs.next()) { System.out.println(rs.getInt(1) + " : " + rs.getString(2) + " (salary = " + rs.getFloat(3) + ")“ ); }//while

// Close the result set, statement // and the connection rs.close(); stmt.close(); connection.close();}

Page 88: Java ain't scary - introducing Java to PL/SQL Developers

PL/SQL PACKAGE PROCESSING AN HTTP REQUEST: THE EMBEDDED PL/SQL GATEWAY

• The Database (the PL/SQL VM) can handle HTTP requests via the Embedded PL/SQL Gateway

• HTTP requests are routed to a custom PL/SQL Package that writes the (usually HTML response)

• The EPG infrastructure handles the actual HTTP response to the invoker

http request

http response Custom PL/SQL package

EPG

htp

Page 89: Java ain't scary - introducing Java to PL/SQL Developers

JAVA CLASS PROCESSING AN HTTP REQUEST: THE SERVLET• The JVM can handle HTTP requests via the

Servlet Container• HTTP requests are routed to a custom Java

Class that writes the (usually HTML response)• The Servlet infrastructure handles the actual

HTTP response to the invokerJVM

Greeter

http request

http responseWebLogic Server

Page 90: Java ain't scary - introducing Java to PL/SQL Developers

HELLO WORLD SERVLETpublic class HelloWorldServlet extends HttpServlet {

private static final String CONTENT_TYPE = "text/html; charset=utf8";

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Hello World</title></head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body></html>"); out.close();}}

Page 91: Java ain't scary - introducing Java to PL/SQL Developers

SERVLET WITH PARAMETERSpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name =null; Object nameParam = request.getParameter("name"); if (nameParam!=null) { name = (String)nameParam; } response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Hello World</title></head>"); out.println("<body>"); if (name!=null) { out.println("<h1>Hello "+name+"!</h1>"); } else { out.println("<h1>Hello World!</h1>"); } out.println("</body></html>"); out.close();}

Page 92: Java ain't scary - introducing Java to PL/SQL Developers

DEMO OF SERVLET THAT WRITES EMPLOYEES TO THE BROWSER PAGE• HTTP request with department id• Response is HTML page with a list of

employees in the department

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Integer departmentIdentifier = null; if (request.getParameter("departmentId") != null) { departmentIdentifier = Integer.parseInt(request.getParameter("departmentId")); } List<String> employeeDetails = new EmployeesCoordinator(). getEmployeeDetails(departmentIdentifier); response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Employees</title></head>"); out.println("<body>"); out.println("<h1>Employees</h1>"); out.println("<ul>"); for (String employee : employeeDetails) { out.println("<li>" + employee + "</li>"); } out.println("</ul>"); out.println("</body></html>"); out.close();}

Page 93: Java ain't scary - introducing Java to PL/SQL Developers

DEMO OF SERVLET THAT WRITES EMPLOYEES TO THE BROWSER PAGE• HTTP request with department id• Response is HTML page with a list of

employees in the department

public class EmployeesCoordinator { public List<String> getEmployeeDetails(Integer departmentId) { List<String> employees = new ArrayList<String>(); Connection connection; try { connection = ConnectionManager.getConnection(); PreparedStatement stmt = connection.prepareStatement("SELECT empno,ename, sal FROM emp WHERE deptno = nvl(?, deptno)"); if (departmentId != null) { stmt.setInt(1, departmentId); // set bind parameter value } ResultSet rs = stmt.executeQuery(); // Loop through the result set while (rs.next()) { employees.add( rs.getInt(1) + " : " + rs.getString(2) + " (salary = " + rs.getFloat(3) + ")"); } // while rs.close(); stmt.close(); connection.close(); } catch (SQLException e) {} // when others then null; return employees; }}

Page 94: Java ain't scary - introducing Java to PL/SQL Developers

SUMMARY

• Java is a 3GL programming language– Similar to PL/SQL in many respects

• Java runs on a JVM - available on almost any platform– PL/SQL runs on database (PL/SQL VM)

• JDeveloper is an IDE (one of many)– Support for edit/refactor/compile/run/debug/…

• Java Class contains properties and methods– Just like PL/SQL package

• Instances of a Class are called Objects– Each Object has ‘state’ (like PL/SQL package in

each database session)• Class can have Sub Classes: more specialized

– Sub Classes inherit methods and properties and add (or override)

– Similar to Sub Types in ERD

Page 95: Java ain't scary - introducing Java to PL/SQL Developers

SUMMARY (2)

• In Java the contract that specifies the functionality provided by a Class is called Interface– Similar to the PL/SQL Package Specification

• An object can be cast in a specific role (to a Class or Interface) if it is an instanceof that Class or Interface– Similar to conversion or casting in PL/SQL

• Through JDBC – Java programs can access relational databases and execute SQL & call PL/SQL

• Servlets are Java Classes that process HTTP Requests and return HTTP Responses – for example to browser– Similar to PL/SQL packages accessed through

EPG (database embedded PL/SQL gateway)

Page 96: Java ain't scary - introducing Java to PL/SQL Developers

NEXT STEPS

• ‘get your hands dirty’

• Internet

• Head First Java

• Download & Install JDeveloper from OTN

• AMIS Training “Java for PL/SQL Developers” (5 day)

Page 97: Java ain't scary - introducing Java to PL/SQL Developers

BUT FIRST…