EJB Access to Databases Using JDBC API

41
1 1 © D. Wong 2003 © D. Wong 2003 EJB Access to Databases Using JDBC EJB Access to Databases Using JDBC API API J2EE uses 1. JDBC 2.0 (java.sql) and 2. JDBC 2.0 Optional package (javax.sql) To make a connection to database in J2EE : 1. Should not hardcode the actual name (URL) of the database in EJB 2. Should refer to the database with a logical name 3. Use a JNDI lookup when obtaining the database connection.

description

EJB Access to Databases Using JDBC API. J2EE uses JDBC 2.0 (java.sql) and JDBC 2.0 Optional package (javax.sql) To make a connection to database in J2EE : Should not hardcode the actual name (URL) of the database in EJB Should refer to the database with a logical name - PowerPoint PPT Presentation

Transcript of EJB Access to Databases Using JDBC API

Page 1: EJB Access to Databases Using JDBC API

11 © D. Wong 2003© D. Wong 2003

EJB Access to Databases Using JDBC APIEJB Access to Databases Using JDBC API

J2EE uses

1. JDBC 2.0 (java.sql) and

2. JDBC 2.0 Optional package (javax.sql)

To make a connection to database in J2EE :

1. Should not hardcode the actual name (URL) of the database in EJB

2. Should refer to the database with a logical name

3. Use a JNDI lookup when obtaining the database connection.

Page 2: EJB Access to Databases Using JDBC API

22 © D. Wong 2003© D. Wong 2003

Driver and Data source properties

In J2EE configuration file, resource.properties, specify: Driver

e.g. 1 Cloudscape that is packaged with Sun’s J2EEjdbcDriver.0.name=COM.cloudscape.core.RmiJdbcDriver

e.g. 2 Oracle jdbcDriver.0.name= oracle.jdbc.driver.OracleDriver

JDBC URL

e.g. 1 Cloudscape

jdbcDataSource.0.name=jdbc/Cloudscape

jdbcDataSource.0.url=jdbc:cloudscape:rmi:CloudscapeDB;create=true

e.g. 2 Oracle

jdbcDataSource.0.name=jdbc/Oracle

jdbcDataSource.0.url= jdbc:oracle:thin:@bigoh.cis.uab.edu:1521:cs610

Page 3: EJB Access to Databases Using JDBC API

33 © D. Wong 2003© D. Wong 2003

Making a connection to database exampleMaking a connection to database example

1. Specify the logical database name.

private String dbName = "java:comp/env/jdbc/AccountDB";

2. Obtain the DataSource associated with the logical name.

InitialContext ic = new InitialContext();

DataSource ds = (DataSource) ic.lookup(dbName);

3. Get the Connection from the DataSource.

Connection con = ds.getConnection(username, password);

Page 4: EJB Access to Databases Using JDBC API

44 © D. Wong 2003© D. Wong 2003

Specifying JNDI name for deployment Step 1: Enter the code name

Page 5: EJB Access to Databases Using JDBC API

55 © D. Wong 2003© D. Wong 2003

Step 2: Map the coded name to the JNDI name

Page 6: EJB Access to Databases Using JDBC API

66 © D. Wong 2003© D. Wong 2003

Persistence ManagementPersistence Management

Container-Managed Persistence

• Entity bean code does not contain database access calls.

• The EJB container generates the SQL statements.

Bean-Managed Persistence• Entity bean code contains the database access calls

(SQLs) (i.e. you write the code!)

Page 7: EJB Access to Databases Using JDBC API

77 © D. Wong 2003© D. Wong 2003

Container Managed example: Product entity bean

ProductEJB.java

ProductHome.java

Product.java

ProductClient.java

Bean Managed example: Account entity bean

AccountEJB.java

AccountHome.java

Account.java

AccountClient.java

Page 8: EJB Access to Databases Using JDBC API

88 © D. Wong 2003© D. Wong 2003

Page 9: EJB Access to Databases Using JDBC API

99 © D. Wong 2003© D. Wong 2003

Page 10: EJB Access to Databases Using JDBC API

1010 © D. Wong 2003© D. Wong 2003

Page 11: EJB Access to Databases Using JDBC API

1111 © D. Wong 2003© D. Wong 2003

Transaction ManagementTransaction Management

Ref. JavaTM 2 Enterprise Edition Developer's Guide

Page 12: EJB Access to Databases Using JDBC API

1414 © D. Wong 2003© D. Wong 2003

J2EE ResourcesJ2EE Resources

• JavaTM 2 SDK, Enterprise Edition Technical DocumentationJavaTM 2 Enterprise Edition Developer's Guide

• http://java.sun.com/j2ee/j2sdkee/

• http://archives.java.sun.com/archives/j2ee-interest.html

• Developing Enterprise Applications with the JavaTM 2 Platform Enterprise Edition http://java.sun.com/j2ee/blueprints/

• Major commercial implementations: •WebLogic - Bea•Websphere - IBM

Page 13: EJB Access to Databases Using JDBC API

1515 © D. Wong 2003© D. Wong 2003

.Net Data Providers.Net Data Providers

Purpose:Purpose:

– connect, read, and execute commands against connect, read, and execute commands against data sourcesdata sources

– other functions, such as the management of other functions, such as the management of input and output parameters, security, input and output parameters, security, transactions, and database server errors.transactions, and database server errors.

Page 14: EJB Access to Databases Using JDBC API

1616 © D. Wong 2003© D. Wong 2003

.NET data provider classes.NET data provider classes

1.1. SqlConnectionSqlConnection

2.2. SqlCommandSqlCommand

3.3. SqlDataReader - can use for read-only SqlDataReader - can use for read-only applications from a SQL Server data sourceapplications from a SQL Server data source

4.4. SqlDataAdapter - acts as a bridge between a SqlDataAdapter - acts as a bridge between a remote SQL Server data source and a DataSet remote SQL Server data source and a DataSet class instance inside a Visual Basic .NET solutionclass instance inside a Visual Basic .NET solution

Page 15: EJB Access to Databases Using JDBC API

1717 © D. Wong 2003© D. Wong 2003

Semi-structured Data Model (Ref. 4.6)Semi-structured Data Model (Ref. 4.6)

Blends class and relation forBlends class and relation for

1.1. Flexibility, therefore suitable for integration Flexibility, therefore suitable for integration of database.of database.

2.2. Serve as a document model in notation such as Serve as a document model in notation such as XMLXML

3.3. Schemaless – the data is “self-describing”, the Schemaless – the data is “self-describing”, the schema is attached to the data itself, which schema is attached to the data itself, which can vary arbitrarily over time and within a can vary arbitrarily over time and within a single db.single db.

Page 16: EJB Access to Databases Using JDBC API

1818 © D. Wong 2003© D. Wong 2003

Semi-structured Data Model UtilitySemi-structured Data Model Utility

An information integration tool to integrate legacy An information integration tool to integrate legacy databasesdatabases

Legacy database problem:Legacy database problem:

The problem of integrating multiple databases The problem of integrating multiple databases designed independently, and used over time for designed independently, and used over time for many different applications.many different applications.

Page 17: EJB Access to Databases Using JDBC API

1919 © D. Wong 2003© D. Wong 2003

Semi-structured Data RepresentationSemi-structured Data Representation

A db of semi-structured data is a collection of A db of semi-structured data is a collection of nodesnodes

Node types:Node types:

– Leaf – have associated data of atomic types (e.g. Leaf – have associated data of atomic types (e.g. numbers, strings)numbers, strings)

– Interior – have 1 or more arcs outInterior – have 1 or more arcs out

– Root – an interior node has no arcs entering it, Root – an interior node has no arcs entering it, representing the entire db (I.e. the entry point)representing the entire db (I.e. the entry point)

Every node must be reachable from the root.Every node must be reachable from the root.

Page 18: EJB Access to Databases Using JDBC API

2020 © D. Wong 2003© D. Wong 2003

Semistructured Data Representation (continued)Semistructured Data Representation (continued)

Arc – has a label to indicate relationship between Arc – has a label to indicate relationship between 2 nodes. Consider arc L connecting nodes M, N, 2 nodes. Consider arc L connecting nodes M, N, the 2 roles that an arc serves:the 2 roles that an arc serves:

1.1. If M is an object, N is an attribute, then L If M is an object, N is an attribute, then L represents the name of the attributerepresents the name of the attribute

2.2. If M and N are both objects, L is the name of If M and N are both objects, L is the name of the relationship from N to Mthe relationship from N to M

The structure is a graph, not necessarily a tree.The structure is a graph, not necessarily a tree.

E.g. Figure 4.19 E.g. Figure 4.19

Page 19: EJB Access to Databases Using JDBC API

2121 © D. Wong 2003© D. Wong 2003

XMLXML

XML : eXensible Markup Language. XML : eXensible Markup Language. Tag-based notation for “marking” documentsTag-based notation for “marking” documents Plain textPlain text Formats of tag: Formats of tag:

1.1. <tag><tag> string of data string of data </tag> </tag>

e.g. <phone>123-456-7890</phone>e.g. <phone>123-456-7890</phone>

2.2. <tag/> <tag/> <!-- empty tag--><!-- empty tag-->

e.g. <flag/>e.g. <flag/> Two modes:Two modes:

– Well-formed XMLWell-formed XML

– Valid XMLValid XML Comment format: Comment format: <!– your comments --><!– your comments -->

Page 20: EJB Access to Databases Using JDBC API

2222 © D. Wong 2003© D. Wong 2003

HTML vs. XMLHTML vs. XML

HTML tagsHTML tags

For describing the presentation of the data (e.g. For describing the presentation of the data (e.g. <B> abc </B>) by a web browser<B> abc </B>) by a web browser

XML tagsXML tags

For describing the meaning of the data (e.g. For describing the meaning of the data (e.g. <phone> 123-456-7890 </phone>)<phone> 123-456-7890 </phone>)

Page 21: EJB Access to Databases Using JDBC API

2323 © D. Wong 2003© D. Wong 2003

Well-formed XMLWell-formed XML

Requirements:Requirements:

Document begin with a declaration (prologue):Document begin with a declaration (prologue):

<?xml version="1.0"? STANDLONE=“yes”?> <?xml version="1.0"? STANDLONE=“yes”?>

It has a root.It has a root.

Every opening tag is followed by a matching closing tag, Every opening tag is followed by a matching closing tag, and the elements are properly nested inside each other.and the elements are properly nested inside each other.

E.g. <BODY> … </BODY>E.g. <BODY> … </BODY>

Any attribute can occur at most once in a given opening Any attribute can occur at most once in a given opening tag, its value must be provided and quoted.tag, its value must be provided and quoted.

E.g Figure 4.21 E.g Figure 4.21

Page 22: EJB Access to Databases Using JDBC API

2424 © D. Wong 2003© D. Wong 2003

Well-formed XML (continued)Well-formed XML (continued)

Invent your own tags.Invent your own tags.

Resembles semi-structure data model:Resembles semi-structure data model:

– SchemalessSchemaless

– Self-describingSelf-describing

– Object likeObject like

Page 23: EJB Access to Databases Using JDBC API

2525 © D. Wong 2003© D. Wong 2003

Valid XMLValid XML

Uses a Document Type Definition (DTD) to Uses a Document Type Definition (DTD) to specify:specify:

– Allowable tagsAllowable tags

– Grammar for how the tags may be nested.Grammar for how the tags may be nested.

More flexible than a strict-schema modelMore flexible than a strict-schema model

– E.g. allow optional or missing fieldsE.g. allow optional or missing fields

More restrictive than a completely schemaless More restrictive than a completely schemaless modelmodel

Page 24: EJB Access to Databases Using JDBC API

2626 © D. Wong 2003© D. Wong 2003

XML elements and Entities/Objects (1)XML elements and Entities/Objects (1)

XML evolved from a document markup language XML evolved from a document markup language (SGML) rather than a database language(SGML) rather than a database language

e.g. <Address>e.g. <Address>John lives on John lives on

<Street> Main St </Street><Street> Main St </Street>

house numberhouse number

<number>123</number><number>123</number>

In a remote townshipIn a remote township

</Address></Address> Mixed data and text is a hindrance for databaseMixed data and text is a hindrance for database

Page 25: EJB Access to Databases Using JDBC API

2727 © D. Wong 2003© D. Wong 2003

XML elements and Entities/Objects (2)XML elements and Entities/Objects (2)

XML elements are ordered whereas the attributes XML elements are ordered whereas the attributes and the tuples in a relation are notand the tuples in a relation are not

E.g. E.g. <Address> <Number>123-4567</Number><Address> <Number>123-4567</Number> <Street>Main St. </Street> <Address><Street>Main St. </Street> <Address> <Address> <Street>Main St. </Street> <Address> <Street>Main St. </Street>

<Number>123-4567</Number> </Address><Number>123-4567</Number> </Address>

But, these tuples are equivalent:But, these tuples are equivalent:

NumberNumber StreetStreet

123-4567123-4567 Main St.Main St.

StreetStreet NumberNumber

Main St.Main St. 123-4567123-4567

Page 26: EJB Access to Databases Using JDBC API

2828 © D. Wong 2003© D. Wong 2003

XML Element typesXML Element types

Complex typesComplex types

– Elements that contain sub-elements or carry attributes Elements that contain sub-elements or carry attributes

e.g. e.g. <message to=“[email protected]"<message to=“[email protected]" from=“[email protected]" from=“[email protected]" subject="XML">

<text><text> XML basics …XML basics … </text></text> </message></message>

Simple typesSimple types

– elements that contain numbers (and strings, and dates, elements that contain numbers (and strings, and dates, etc.) but do not contain any subelements etc.) but do not contain any subelements

– Built-in or author definedBuilt-in or author defined Attributes always have simple types. Attributes always have simple types.

Page 27: EJB Access to Databases Using JDBC API

2929 © D. Wong 2003© D. Wong 2003

Document Type Definition (DTD)Document Type Definition (DTD)

It’s set of rules for constructing an XML document.It’s set of rules for constructing an XML document.

– i.e. a grammar that specifies the schema of a legal i.e. a grammar that specifies the schema of a legal XML documentXML document

Specified by XML authors:Specified by XML authors:

– As part of the document itself, orAs part of the document itself, or

– Stored separate from the document. The Stored separate from the document. The document refers to the URL where the DTD is document refers to the URL where the DTD is stored.stored.

An XML document that conforms to it’s DTD is An XML document that conforms to it’s DTD is said to be valid.said to be valid.

Page 28: EJB Access to Databases Using JDBC API

3030 © D. Wong 2003© D. Wong 2003

DTD StructureDTD Structure

Basic DTD structure:Basic DTD structure:<!DOCTYPE root-tag [<!DOCTYPE root-tag [

<!ELEMENT element-name(components)><!ELEMENT element-name(components)>more elementsmore elements

]>]>

The name of the DTD must coincide with the tag name of The name of the DTD must coincide with the tag name of the root element of the document that conforms to that the root element of the document that conforms to that DTD.DTD.

One ELEMENT statement for each allowed tag, including One ELEMENT statement for each allowed tag, including the root tagthe root tag

For each tag that can have attributes, the ATTLIST For each tag that can have attributes, the ATTLIST statement specifies the allowed attributes and their type.statement specifies the allowed attributes and their type.

Component of #PCDATA means simple text (i.e. no tags Component of #PCDATA means simple text (i.e. no tags nested within)nested within)

Page 29: EJB Access to Databases Using JDBC API

3131 © D. Wong 2003© D. Wong 2003

DTD Structure (continue)DTD Structure (continue)

Component occurrence indicators:Component occurrence indicators:

– * : zero or more * : zero or more

– + : one or more+ : one or more

– ? : zero or one time? : zero or one time

– | : either or | : either or

e.g. (#PCDATA | (STREET CITY)e.g. (#PCDATA | (STREET CITY) Empty tags: <!ELEMENT elementName, EMPTY>Empty tags: <!ELEMENT elementName, EMPTY>

e.g. <!ELEMENT Flag EMPTY>e.g. <!ELEMENT Flag EMPTY> E.g. Figure 4.22 (2n. Ed.) – a DTD for movie starsE.g. Figure 4.22 (2n. Ed.) – a DTD for movie stars Figure 4.23 (2n. Ed.) – a document following DTD in Figure 4.23 (2n. Ed.) – a document following DTD in

Figure 4.22Figure 4.22

Page 30: EJB Access to Databases Using JDBC API

3232 © D. Wong 2003© D. Wong 2003

Using a DTDUsing a DTD

Two ways:Two ways:

1.1. Include the DTD at the beginning of the Include the DTD at the beginning of the documentdocument

2.2. In the document’s opening line, refer to the In the document’s opening line, refer to the DTD that is stored separately in a file system DTD that is stored separately in a file system accessible to the application that is processing accessible to the application that is processing the document.the document.

e.g. e.g.

<?XML VERSION = “1.0” STANDALONE = “no”?><?XML VERSION = “1.0” STANDALONE = “no”?>

<!DOCTYPE Stars SYSTEM “star.dtd”><!DOCTYPE Stars SYSTEM “star.dtd”>

Page 31: EJB Access to Databases Using JDBC API

3333 © D. Wong 2003© D. Wong 2003

Attribute ListsAttribute Lists

Format:Format:

<!ATTLIST ElementName <!ATTLIST ElementName

attributeName type [Modifier]attributeName type [Modifier]

. . .. . .

>>

Page 32: EJB Access to Databases Using JDBC API

3434 © D. Wong 2003© D. Wong 2003

Some attribute typesSome attribute types

1.1. CDATA CDATA <!-- simple text --><!-- simple text -->

2.2. IDID An attribute of type ID must have a unique value through An attribute of type ID must have a unique value through

out the document out the document E.g. if attr1 and attr2 are ID type, then E.g. if attr1 and attr2 are ID type, then

<elt1 attr1="123"> and <elt2 attr2="123"> is illegal<elt1 attr1="123"> and <elt2 attr2="123"> is illegal Imitate key in relational dbImitate key in relational db

3.3. IDREFIDREF An attribute of type IDREF must refer to a valid ID An attribute of type IDREF must refer to a valid ID

declared in the same documentdeclared in the same document Imitate foreign keyImitate foreign key

4.4. IDREFSIDREFS Refer to a list of valid IDs declared in the documentRefer to a list of valid IDs declared in the document

Page 33: EJB Access to Databases Using JDBC API

3535 © D. Wong 2003© D. Wong 2003

Some Modifier TypesSome Modifier Types

#IMPLIED#IMPLIED

– The attribute is optional.The attribute is optional.

– Can remain unspecifiedCan remain unspecified

#REQUIRED#REQUIRED

– The attribute is mandatory.The attribute is mandatory.

– E.g. movieId ID #REQUIREDE.g. movieId ID #REQUIRED

Page 34: EJB Access to Databases Using JDBC API

3636 © D. Wong 2003© D. Wong 2003

Example: Use DTD to alleviate the order problemExample: Use DTD to alleviate the order problem

E.g.:E.g.:

<!ELEMENT Person ((Name, Id, Address) | <!ELEMENT Person ((Name, Id, Address) | (Name, Address, Id) | (Id, Address, Name) | (Id, (Name, Address, Id) | (Id, Address, Name) | (Id, Name, Address) | (Address, Id, Name) | (Address, Name, Address) | (Address, Id, Name) | (Address, Name, Id))>Name, Id))>

But, it's awkward!But, it's awkward!

Page 35: EJB Access to Databases Using JDBC API

3737 © D. Wong 2003© D. Wong 2003

XML SchemaXML Schema

A DDL for XML documentsA DDL for XML documents

Purpose: to define a class of XML documentsPurpose: to define a class of XML documents

Instance document: an XML document that Instance document: an XML document that conforms to a particular schema (schema valid). conforms to a particular schema (schema valid).

Instances and schemas may exist as:Instances and schemas may exist as:

– documents in filesdocuments in files

– streams of bytes sent between applicationsstreams of bytes sent between applications

– fields in a database recordfields in a database record

– collections of XML "Infoset "Information Itemscollections of XML "Infoset "Information Items

Page 36: EJB Access to Databases Using JDBC API

3838 © D. Wong 2003© D. Wong 2003

TriggersTriggers

Available in Oracle and SQL99Available in Oracle and SQL99

Event-Condition-Action rules: define an action Event-Condition-Action rules: define an action the db should take when some db-related events the db should take when some db-related events occursoccurs

Page 37: EJB Access to Databases Using JDBC API

3939 © D. Wong 2003© D. Wong 2003

Trigger vs. other constraintsTrigger vs. other constraints

1.1. Triggers are awakened when certain events, Triggers are awakened when certain events, specified by db programmer, occur. E.g. update, specified by db programmer, occur. E.g. update, insert, delete to a relation; end of a transactioninsert, delete to a relation; end of a transaction

2.2. Other constraints immediately prevent the event Other constraints immediately prevent the event if the constraint is violated. For trigger, it's if the constraint is violated. For trigger, it's condition is tested when the event occurs, if the condition is tested when the event occurs, if the condition does not hold, then the action condition does not hold, then the action associated with the trigger will not happen (I.e. associated with the trigger will not happen (I.e. trigger will not be fired)trigger will not be fired)

3.3. If the trigger condition is true, the action is If the trigger condition is true, the action is performed by the DBMS (I.e. trigger fired). So, performed by the DBMS (I.e. trigger fired). So, it's transparent to the userit's transparent to the user

Page 38: EJB Access to Databases Using JDBC API

4040 © D. Wong 2003© D. Wong 2003

Trigger SyntaxTrigger Syntax

CREATE [OR REPLACE] TRIGGER <triggerName>CREATE [OR REPLACE] TRIGGER <triggerName>

{BEFORE | AFTER | INSTEADOF}{BEFORE | AFTER | INSTEADOF}

{DELETE | INSERT | UPDATE [of column, …] }{DELETE | INSERT | UPDATE [of column, …] }

[OR {DELETE | INSERT | UPDATE [of column, …] }[OR {DELETE | INSERT | UPDATE [of column, …] }

ON {tableName | viewName}ON {tableName | viewName}

[REFERENCING { OLD [AS] <oldName> , NEW [AS] [REFERENCING { OLD [AS] <oldName> , NEW [AS] <newName> …]<newName> …]

FOR EACH {ROW | STATEMENT} FOR EACH {ROW | STATEMENT}

[WHEN (condition) ] <action>;[WHEN (condition) ] <action>;

Page 39: EJB Access to Databases Using JDBC API

4141 © D. Wong 2003© D. Wong 2003

Oracle TriggersOracle Triggers

<action> is PL/SQL block<action> is PL/SQL block

Simplest is :Simplest is :

BEGINBEGIN

<SQL statement><SQL statement>

END;END;

In the PL/SQL action block, variables OLD and NEW are preceded In the PL/SQL action block, variables OLD and NEW are preceded by : e.g. :OLDby : e.g. :OLD

Follow the create trigger statement with a Dot (.) and then RUN to Follow the create trigger statement with a Dot (.) and then RUN to store the definition in the dbstore the definition in the db

The action cannot change the relation that triggers the action, nor to The action cannot change the relation that triggers the action, nor to relations connected to the triggering relation by a constraint e.g. FK relations connected to the triggering relation by a constraint e.g. FK constraintconstraint

Read 7.4.2 – 7.4.4Read 7.4.2 – 7.4.4

Page 40: EJB Access to Databases Using JDBC API

4242 © D. Wong 2003© D. Wong 2003

SQL3 TriggersSQL3 Triggers

<action> can be:<action> can be:

1.1. a single SQL statementa single SQL statement

2.2. A SQL statements, separated by ; enclosed in a A SQL statements, separated by ; enclosed in a

BEGINBEGIN

<SQL statements><SQL statements>

END;END;

Page 41: EJB Access to Databases Using JDBC API

4343 © D. Wong 2003© D. Wong 2003

Constraints SummaryConstraints Summary

1.1. Primary Key declarationPrimary Key declaration

2.2. Foreign Key – referential integrity constraintForeign Key – referential integrity constraint

3.3. Constraints within relations:Constraints within relations:

Attribute constraints: 1. NOT NULL; 2. Attribute constraints: 1. NOT NULL; 2. CHECKCHECK

Tuple based CHECKsTuple based CHECKs

4.4. Schema level constraints – SQL2 assertions (not Schema level constraints – SQL2 assertions (not in Oracle)in Oracle)

5.5. Triggers – Oracles's and SQL99'sTriggers – Oracles's and SQL99's