datubaze.files.wordpress.com€¦ · web view2019-12-02 · informācijas sistēmas...
TRANSCRIPT
Informācijas sistēmas arhitektūra
"thick" client"thin" client Lietojumi Web serveris Transakciju serveris ODBC Relāciju datu bāze OLE DB Objektu datu bāze ADO Relāciju-objektu datu bāze JDBC Universālās datu bāzes
Datu bāzes sistēma
Datu bāzes
vadības instance
Dat
u bā
zes i
nter
feis
sLietojumu serveris
Objektu-relāciju
attēlojums (ORM)
"plānais" klients
Datu bāze
Dati un meta-dati
Servera procedūras
(PL/SQL, Java)
"biezais" klients
Oracle datu bāzes Java komponenšu struktūra
Oracle Java applications reside on top of the Java core class libraries, which reside on top of the JVM. Because the Oracle Java support system is located within the database, the JVM interacts with Oracle Database libraries, instead of directly interacting with the operating system.
Sun Microsystems provides publicly available specifications for both the Java language and the JVM. The JLS defines the syntax and semantics, and JVM specification defines the necessary low-level actions for the system that runs the application. In addition, Sun Microsystems provides a compatibility test suite for JVM implementors to determine if they have complied with the specifications. This test suite is known as the Java Compatibility Kit (JCK). Oracle JVM implementation complies fully with JCK. Part of the overall Java strategy is that an openly specified standard, together with a simple way to verify compliance with that standard, allows vendors to offer uniform support for Java across all platforms.
2
Java Virtual Machine
The Java source compiles to low-level computer instructions. In Java, these instructions are known as bytecodes, because each instruction has a uniform size of one byte. Most other languages, such as C, compile to computer-specific instructions, such as instructions specific to an Intel or HP processor. When compiled, the Java code gets converted to a standard, platform-independent set of bytecodes, which are executed by a Java Virtual Machine (JVM). A JVM is a separate program that is optimized for the specific platform on which you run your Java code.
The Java bytecodes get interpreted through the JVM into the appropriate platform dependent actions.
When you develop a Java application, you use predefined core class libraries written in the Java language. The Java core class libraries are logically divided into packages that provide commonly used functionality. Basic language support is provided by the java.lang package, I/O support is provided by the java.io package, and network access is provided by the java.net package. Together, a JVM and the core class libraries provide a platform on which Java programmers can develop applications, which will run successfully on any operating system that supports Java. This concept is what drives the "write once, run anywhere" idea of Java.
Java lietojums
Java virtuālā mašīna
operētājsistēma
3
4
Java lietojumi
You can write and load Java applications within the database because it is a safe language with a lot of security features. Java has been developed to prevent anyone from tampering with the operating system where the Java code resides in. Some languages, such as C, can introduce security problems within the database. However, Java, because of its design, is a robust language that can be used within the database.Oracle Database provides Java applications with a dynamic data-processing engine that supports complex queries and different views of the same data. All client requests are assembled as data queries for immediate processing, and query results are generated dynamically.The combination of Java and Oracle Database helps you to create component-based, network-centric applications that can be easily updated as business needs change. In addition, you can move applications and data stores off the desktop and onto intelligent networks and network-centric servers. More important, you can access those applications and data stores from any client device.
5
Datu bāzes sesija
In the Java-integrated Oracle Database, your Java applications exist within the context of a database session. Each Oracle JVM session maintains the state of the Java applications accessed by the client across calls within the session. Each Java database session has a separate garbage collector, session memory, and call memory.Within the context of a session, the client performs the following:
1) connects to the database and opens a session;2) runs Java within the database. This is referred to as a call;3) continues to work within the session, performing as many calls as required;4) ends the session.
Within a session, the client has its own Java environment. It appears to the client as if a separate, individual JVM was started for each session, although the implementation is more efficient than this seems to imply. Within a session, Oracle JVM manages the scalability of applications. Every call from a single client is managed within its own session, and calls from each client are handled separately. Oracle JVM maximizes sharing read-only data between clients and emphasizes a minimum amount of per-session incremental footprint, to maximize performance for multiple clients.The underlying server environment hides the details associated with session, network, state, and other shared resource management issues from the Java code. Fields defined as static are local to the client. No client can access the static fields of other clients, because the memory is not available across session boundaries. Because each client runs the Java application calls within its own session, activities of each client are separate from any other client. During a call, you can store objects in static fields of different classes, which will be available in the next call. The entire state of your Java program is private and exists for your entire session.Oracle JVM manages the following within the session:
1) All the objects referenced by static Java fields, all the objects referred to by these objects, and so on, till their transitive closure
6
2) Garbage collection for the client that created the session3) Session memory for static fields and across call memory needs4) Call memory for fields that exist within a call
7
Java metodes izsaucošās (call specs) PL/SQL procedūras
To publish Java methods, you write call specs. For a given Java method, you declare a function or procedure call spec using the SQL CREATE FUNCTION or CREATE PROCEDURE statement. You publish value-returning Java methods as functions or procedures and void Java methods as procedures. The function or procedure body contains the LANGUAGE JAVA clause.
As an alternative, use the native Java interface to directly invoke Java in the database from a Java client. A call spec and the Java method it publishes must reside in the same schema (unless the Java method has a PUBLIC synonym). You can declare the call spec as a:
1) standalone (top-level) PL/SQL function or procedure;2) packaged PL/SQL function or procedure;3) member method of a SQL object type.
A call spec exposes a Java method's top-level entry point to Oracle. Therefore, you can publish only public static methods—with one exception. You can publish instance methods as member methods of a SQL object type.Packaged call specs perform as well as top-level call specs. So, to ease maintenance, you might want to place call specs in a package body. That way, you can modify them without invalidating other schema objects. Also, you can overload them.
Lietojums PL/SQL izsaucošāprocedūra vai funkcija (Call Spec)
Java metode
Datu vārdnīca
Datu bāze
8
Java programmas izpildes varianti
9
Savienojuma ar DB veidošanas draiveri
1. JDBC Thin DriverYou can use the JDBC Thin driver to write 100% pure Java applications and applets that access Oracle SQL data. The JDBC Thin driver is especially well-suited to Web browser-based applications and applets, because you can dynamically download it from a Web page just like any other Java applet.
2. JDBC Oracle Call Interface DriverThe JDBC Oracle Call Interface (OCI) driver accesses Oracle-specific native code (that is, non-Java) libraries on the client or middle tier, providing some performance boost compared to the JDBC Thin driver, at the cost of significantly larger size and client-side installation.
3. JDBC Server-side Internal DriverOracle Database uses the server-side internal driver when Java code executes on the server. It allows Java applications executing in the server's Java virtual machine to access locally defined data (that is, on the same machine and in the same process) with JDBC. It provides a further performance boost because of its ability to use underlying Oracle RDBMS libraries directly, without the overhead of an intervening network connection between your Java code and SQL data. By supporting the same Java-SQL interface on the server, Oracle Database does not require you to rework code when deploying it.
10
DB glabājamās procedūras (stored procedures)
Oracle javas virtuālā mašīna OracleJVM nodrošina sekojošu programmu izpildi:1) funkciju un procedūru;
2) trigeru;
3) relāciju-objektu metožu.
11
Vai Java programmēšanas valodas lietošanas iespējas ir nodrošinātas datu bāzē (vai ir Java Virtual Machine (JVM) "aurora")
Sākot ar Oracle8i versiju datu bāzes serverī ir iekļauta Java Virtual Machine, kas ļauj izmantot un veidot serverī Java klases.1
select COUNT(*) from ALL_OBJECTS where OBJECT_TYPE like 'JAVA%';
1 Ken Arnold, James Gosling, David Holmes. The Java Programming Language. Addison-Wesley.David Flanagan. Java in a Nutshell. O'Reilly.Bruce Eckel. Thinking in Java. Prentice Hall.
12
Java Memory Areas
In OracleJVM, the states of Java objects are preserved in special data structurescalled “object memories.” There are several object memory types:
1) newspace is the default memory for allocating almost all Java objects, except large objects, which are allocated in Oldspace.
2) oldspace is an object memory used for holding long-lived or large objects (i.e., larger than 1-K Bytes) for the duration of a call.
3) runspace is an object memory residing in CGA or PGA and is used to hold system objects (e.g., classloader objects) allocated for the duration of a call.
4) stackspace is an object memory residing in CGA or PGA and is used to allocate system objects and objects used by the Java interpreter (no user objects);
5) sessionspace, also called “session memory,” is an object memory residing in the User Global Area (UGA), which is associated with each session (each session has its own Sessionspace) and lives as long as the session lives. Sessionspace is used to preserve state of system objects, user objects, and metadata used by the Java runtime.
13
Java atmiņas apgabali izdalītā servera gadījumā
14
Java atmiņas apgabali koplietojuma servera gadījumā
15
A Java application may result in:1) of bytecodes (interpreted);2) natively compiled binaries. Therefore, the natively compiled code must be fully interoperable with the Java VM. The native compiler has been designed to generate C code that allows natively compiled routines to call (and be called from) interpreted Java bytecode.
16
Serverī glabājamas Java valodas procedūras (stored procedures) izveidošanas un izmantošanas piemērs1. Java klases definējuma ierakstīšana Sveiki.java failā.
public class Sveiki {public static String Teksts () { return "Sveiki! Sāksim lietot Javu datu bāzē."; } }
2. Java klases ielādēšana datu bāzē. Var veikt *.java vai *.class faila ielādi.
Failu glabāšanas katalogi:H:\oracle\product\10.1.0\Db_1\BIN\loadjava.bat H:\Java\Sveiki.javaKomandu fails ar saviem parametriem tiek palaists no kataloga H:\Java.
loadjava.bat -u sakne/janis@localhost:1521:BAZE –v –r -t Sveiki.java
option -v enables verbose (izplūdis) mode;option -r compiles uploaded Java source files and resolves external references in the classes;option -t tells loadjava to connect to the database using the client-side JDBC Thin driver.
3. Klases ielādes pārbaude (no SQL*Plus programmas).col OBJECT_NAME format a30;col OBJECT_TYPE format a15;select OBJECT_NAME, OBJECT_TYPE, STATUSfrom USER_OBJECTS;
OBJECT_NAME OBJECT_TYPE STATUS---------------------------------------------------------------------------------JAVA$OPTIONS TABLE VALIDSveiki JAVA CLASS VALIDSveiki JAVA SOURCE VALID
17
Serverī glabājamas Java valodas procedūras (stored procedures) izveidošanas un izmantošanas piemērs (turpinājums)
4. Java metodi izsaucošās PL/SQL funkcijas izveidošana .
create or replace function SVEIKI_TEKSTS return varchar2 as language java name 'Sveiki.Teksts () return java.lang.String';
5. Metadatu apskate.
select OBJECT_NAME, OBJECT_TYPE, STATUSfrom USER_OBJECTS;
OBJECT_NAME OBJECT_TYPE STATUS-------------------------------------------------------------------------JAVA$OPTIONS TABLE VALIDSveiki JAVA CLASS VALIDSveiki JAVA SOURCE VALIDSVEIKI_TEKSTS FUNCTION VALID
6. Datu bāzes un Java buferu inicializācija.SQL>set serveroutput ON;SQL>call DBMS_JAVA.SET_OUTPUT(2000);
7. Izsaucošās PL\SQL funkcijas aktivēšana ar call izsaukumu.
SQL>variable mainigais_1 varchar2(40);SQL> call SVEIKI_TEKSTS() into :mainigais_1;SQL>print mainigais_1;
mainigais_1---------------------------------------Sveiki! Sāksim lietot Javu datu bāzē.
8. Izsaucošās PL\SQL funkcijas aktivēšana izmantojot SELECT vaicājumu.
select SVEIKI_TEKSTS from DUAL;SVEIKI_TEKSTS-----------------------------------------------Sveiki! Saksim lietot Javu datu bāzē.
!
18
Serverī glabājamas Java valodas procedūras (stored procedures) izveidošanas un izmantošanas piemērs (turpinājums)
9. Ielādētās klases nodzēšana ar komandu dropjava.
OS vidē (RUN cmd ...) jāpalaiž komanda:dropjava -thin -u sakne/janis@localhost:1521:BAZE Sveiki.java
10. Metadatu apskate.select OBJECT_NAME, OBJECT_TYPE, STATUSfrom USER_OBJECTS;
OBJECT_NAME OBJECT_TYPE STATUS-------------------------------------------------------------------------SVEIKI_TEKSTS FUNCTION VALID
19
Serverī glabājamas Java valodas procedūras (stored procedures) izveidošanas un izmantošanas piemērs (turpinājums)
12. Klases ielāde izmantojot CREATE JAVA SOURCE NAMED komandu.
create or replace JAVA source named "Sveiki" aspublic class Sveiki {public static String Teksts (){ return "Sveiki! Sāksim lietot Java datu bāzē."; } };
13. Metadatu apskate. select OBJECT_NAME, OBJECT_TYPE, STATUSfrom USER_OBJECTS;OBJECT_NAME OBJECT_TYPE STATUS------------------------------------------------------------------------------------Sveiki JAVA CLASS INVALIDSveiki JAVA SOURCE INVALIDSVEIKI_TEKSTS FUNCTION VALID
14. Izsaucošās PL/SQL funkcijas pārdefinēšana.
create or replace function SVEIKI_TEKSTS return varchar2 as language java name 'Sveiki.Teksts () return java.lang.String';
15. Izsaucošās PL\SQL funkcijas aktivēšana izmantojot SELECT vaicājumu.
select SVEIKI_TEKSTS from DUAL;SVEIKI_TEKSTS-----------------------------------------------Sveiki! Saksim lietot Javu datu bāzē.
20
Serverī glabājamas Java valodas procedūras (stored procedures) izveidošanas un izmantošanas piemērs (turpinājums)
16. Java objektu nodzēšana no DBVS vides ar komandu drop java
drop java source "Sveiki";drop java class "Sveiki"; 17. Izmantotās simbolu koda tabulas noteikšana
variable m1 varchar2(50);call DBMS_JAVA.GET_COMPILER_OPTION(NULL, 'encoding') into :m1;print m1;m1------------------------WINDOWS-1252
21
Piemērs main metodes parametru transformācijai
As a rule, Java names and call spec parameters must correspond one to one. However, that rule does not apply to method main. Its String[] parameter can be mapped to multiple CHAR or VARCHAR2 call spec parameters.
Faila F:\Atbalss.java saturs:
public class Atbalss { public static void main (String[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } }
loadjava -u java_liet/janis@DATORS:1521:BAZE –v –r -t F:\Atbalss.java
create or replace procedure ATBALSS ( s1 varchar2, s2 varchar2, s3 varchar2)as language JAVA name 'Atbalss.main(java.lang.String[])';
call ATBALSS('AAA', 'BBB', 'CCC');
Rezultāts:AAABBBCCC
You cannot impose constraints (such as precision, size, or NOT NULL) on call spec parameters. So, you cannot specify a maximum size for the VARCHAR2 parameters.
22
Skata USER_OBJECTS kolonas
Column Datatype NULL Description
OWNER VARCHAR2(30) NOT NULL
Owner of the object
OBJECT_NAME VARCHAR2(30) NOT NULL
Name of the object
SUBOBJECT_NAME VARCHAR2(30) Name of the subobject (for example, partition)
OBJECT_ID NUMBER NOT NULL
Dictionary object number of the object
DATA_OBJECT_ID NUMBER Dictionary object number of the segment that contains the object
Note: OBJECT_ID and DATA_OBJECT_ID display data dictionary metadata. Do not confuse these numbers with the unique 16-byte object identifier (object ID) that the Oracle Database assigns to row objects in object tables in the system.
OBJECT_TYPE VARCHAR2(19) Type of the object (such as TABLE, INDEX)
CREATED DATE NOT NULL
Timestamp for the creation of the object
LAST_DDL_TIME DATE NOT NULL
Timestamp for the last modification of the object resulting from a DDL statement (including grants and revokes)
TIMESTAMP VARCHAR2(20) Timestamp for the specification of the object (character data)
STATUS VARCHAR2(7) Status of the object (VALID, INVALID, or N/A)
TEMPORARY VARCHAR2(1) Whether the object is temporary (the current session can see only data that it placed in this object itself)
GENERATED VARCHAR2(1) Was the name of this object system generated? (Y|N)
SECONDARY VARCHAR2(1) Whether this is a secondary object created by the ODCIIndexCreate method of the Oracle Data Cartridge (Y | N)
23
Skata DBA_JAVA_CLASSES kolonas
Column Datatype NULL DescriptionOWNER VARCHAR2(30) NOT
NULLOwner of the Java class
NAME VARCHAR2(4000) Name of the Java classMAJOR NUMBER Major version number of the Java class, as defined in
the JVM specificationMINOR NUMBER Minor version number of the Java class, as defined in
the JVM specificationKIND VARCHAR2(9) Indicates whether the stored object is a Java class
(CLASS) or a Java interface (INTERFACE)ACCESSIBILITY VARCHAR2(6) Accessibility of the Java classIS_INNER VARCHAR2(3) Indicates whether this Java class is an inner class
(YES) or not (NO)IS_ABSTRACT VARCHAR2(3) Indicates whether this Java class is an abstract class
(YES) or not (NO)IS_FINAL VARCHAR2(3) Indicates whether this Java class is a final class (YES)
or not (NO)IS_DEBUG VARCHAR2(3) Indicates whether this Java class contains debug
information (YES) or not (NO)SOURCE VARCHAR2(4000) Source designation of the Java classSUPER VARCHAR2(4000) Super class of this Java classOUTER VARCHAR2(4000) Outer class of this Java class if this Java class is an
inner class
24
Datu ievade tabulā izmantojot Java klasi Firma un metodi FirmaInsert1. Tabulas izveidošanacreate table FIRMAS(F_NUM number Primary key,F_NOS varchar2(30),DIB_DAT varchar2(10));
2. Klases Firma koda ierakstīšana failā O:\Firma.javaimport java.sql.*;import java.io.*;import oracle.jdbc.*;public class Firma{ public static void FirmaInsert (int f_num, String f_nos, String dib_dat) throws SQLException {String sql = "insert into FIRMAS values (?,?,?)"; try {Connection conn = DriverManager.getConnection("jdbc:default:connection:"); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, f_num); pstmt.setString(2, f_nos); pstmt.setString(3, dib_dat); pstmt.executeUpdate(); pstmt.close(); } catch (SQLException e) {System.err.println(e.getMessage());} } }
3. Klases Firma koda ielāde datu bāzē (tiek izmantots CMD)Ielādes komanda:O:\oracle\product\10.1.0\Db_1\bin\loadjava -u system/janis@DATORS:1521:BAZE –v –r -t O:\Firma.java
static – elements, kurš pieder klasei, bet nepieder klases eksemplāriem.void – metodes, kura neatgriež nekādu vērtību, apzīmētājs.throws – ģenerē īpašās situācijas, kuras var izveidoties metodē.try – bloks, kurš piedalās īpašo situāciju pārtveršanā.catch – īpašās situācijas (ja tāda izveidojas blokā, kurš definēts ar throws) apstrāde.
25
4. Programmu paketes PAKETE_F ar PL/SQL procedūru FIRMA_INSERT, kura izsauc klases Firma metodi FirmaInsert, izveide create or replace package PAKETE_F as procedure FIRMA_INSERT (f_num number, f_nos varchar2, dib_dat varchar2);end PAKETE_F;
create or replace package body PAKETE_F as procedure FIRMA_INSERT(f_num number, f_nos varchar2, dib_dat varchar2) as language JAVA name 'Firma.FirmaInsert(int, java.lang.String, java.lang.String)';end PAKETE_F;
5. PL/sql procedūras FIRMA_INSERT izsaukšana
sql>call PAKETE_F.FIRMA_INSERT(1, 'AAA', '21-FEB-01');
6. Datu bāzes tabulas FIRMAS satura apskateselect * from FIRMAS; F_NUM F_NOS DIB_DAT--------------------------------------------------------------- 1 AAA 21-FEB-01
7. Metadatu apskateselect OBJECT_NAME, OBJECT_TYPE, STATUSfrom USER_OBJECTS;OBJECT_NAME OBJECT_TYPE STATUS-------------------------------------------------------------------------Firma JAVA CLASS VALIDFirma JAVA SOURCE VALIDPAKETE_F PACKAGE VALIDPAKETE_F PACKAGE BODY VALID
26
Datu izguve no tabulas FIRMAS izmantojot Java klasi Firma, metodes FirmaSelect un Izvade
1. Iepriekšējā klases definējuma nodzēšanaO:\oracle\product\10.1.0\Db_1\bin\dropjava -thin -u system/janis@DATORS:1521:BAZE O:\Firma.java
2. Klases Firma definējuma ierakstīšana failā FIRMAS.javaimport java.sql.*;import java.io.*;import oracle.jdbc.*;public class Firma{static void Izvade (ResultSet rset) throws SQLException { String buffer = ""; try { ResultSetMetaData meta = rset.getMetaData(); int cols = meta.getColumnCount(), rows = 0; for (int i = 1; i <= cols; i++) {int size = meta.getPrecision(i); String label = meta.getColumnLabel(i); if (label.length() > size) size = label.length(); while (label.length() < size) label += " "; buffer = buffer + label + " "; } buffer = buffer + "\n"; while (rset.next()) { rows++; for (int i = 1; i <= cols; i++) { int size = meta.getPrecision(i); String label = meta.getColumnLabel(i); String value = rset.getString(i); if (label.length() > size) size = label.length(); while (value.length() < size) value += " "; buffer = buffer + value + " "; } buffer = buffer + "\n"; } if (rows == 0) buffer = "No data found!\n"; System.out.println(buffer); } catch (SQLException e) {System.err.println(e.getMessage());} } public static void FirmaSelect (String f_nos) throws SQLException { String sql = "select A.F_NUM, A.F_NOS, A.DIB_DAT " + " from FIRMAS A" + " where A.F_NOS = ?"; try { Connection conn = DriverManager.getConnection("jdbc:default:connection:"); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, f_nos); ResultSet rset = pstmt.executeQuery(); Izvade(rset); rset.close(); pstmt.close(); } catch (SQLException e) {System.err.println(e.getMessage());} } }
27
3. Klases Firma ielāde datu bāzēO:\oracle\product\10.1.0\Db_1\bin\loadjava -u system/janis@DATORS:1521:BAZE –v –r -t O:\Firma.java
4. PL/SQL paketes un izsaucošās procedūras izveidošanacreate or replace package PAKETE_F as procedure FIRMA_INSERT (f_num number, f_nos varchar2, dib_dat varchar2); procedure Firma_SELECT (f_nos varchar2);end PAKETE_F;
create or replace package body PAKETE_F as procedure FIRMA_INSERT(f_num number, f_nos varchar2, dib_dat varchar2) as language JAVA name 'Firma.FirmaInsert(int, java.lang.String, java.lang.String)';
procedure FIRMA_SELECT (f_nos varchar2) as language JAVA name 'Firma.FirmaSelect(java.lang.String)';end PAKETE_F;
5. Metadatu izvade
col OBJECT_NAME format a30;col OBJECT_TYPE format a15;select OBJECT_NAME, OBJECT_TYPE, STATUSfrom USER_OBJECTS;OBJECT_NAME OBJECT_TYPE STATUS------------------------------------------------------------------------------Firma JAVA CLASS VALIDFirma JAVA SOURCE VALIDPAKETE_F PACKAGE VALIDPAKETE_F PACKAGE BODY VALIDFIRMAS TABLE VALID
6. Eksistējošo datu nodzēšana un jauno ievade datu bāzes tabulā FIRMAS
delete FIRMAS;insert into FIRMAS values(1, 'CCC', '21-07-1990');
7. Izsaucošās PL/SQL procedūras FIRMA_SELECT aktivizēšana
SQL> SET SERVEROUTPUT ONSQL> CALL dbms_java.set_output(2000);SQL> CALL PAKETE_F.FIRMA_SELECT('CCC');F_NUM F_NOS DIB_DAT 1 CCC 21-07-1990
28