Table of Contents

~~SLIDESHOW~~

Enterprise Integration-Tier Services

Lecture Contents

What is a Database?

What is a Relational Database?

Relational databases are most common form of database:

An example: CDs from a Music Collection

Artist Title Category Year
The CurePornographyAlternative1983
GarbageGarbageAlternative1996
HoleLive Through ThisAlternative1994
Nine Inch NailsThe Downward SpiralIndustrial1994
Public Image LimitedCompact DiskAlternative1985
The Sex PistolsNever Mind the Bollocks: Here's the Sex PistolsPunk1977
Skinny PuppyLast RightsIndustrial1992
WireA Bell is a Cup Until it is StruckAlternative1989

Johnny Rotten Night for a Party

Last nameFirst nameNickname
JourgensonAl
LydonJohnJohnny Rotten
SmithRobert

Keys (1)

In order to relate musicians to bands and bands to CDs we need a unique key to the data.

album_id Artist Title Category Year
1The CurePornographyAlternative1983
2GarbageGarbageAlternative1996
3HoleLive Through ThisAlternative1994
4Nine Inch NailsThe Downward SpiralIndustrial1994
5Public Image LimitedCompact DiskAlternative1985
6The Sex PistolsNever Mind the Bollocks: Here's the Sex PistolsPunk1977
7Skinny PuppyLast RightsIndustrial1992
8WireA Bell is a Cup Until it is StruckAlternative1989

Keys (2)

In order to relate musicians to bands and bands to CDs we need a unique key to the data.

artist_idLast nameFirst nameNickname
1JourgensonAl
2LydonJohnJohnny Rotten
3SmithRobert

Logical Data Model for Sample Database

Logical data model


Interpretation of the logical data model:

Physical Data Model

physical data model

UML to Physical Data

UML to physical data


Classes, objects, properties and methods:

  1. Class maps to table
  2. Each object will be a row in the table
  3. Each property will be a column in the table
  4. Only properties are stored, no place in the database for methods.

Associations:

  1. One to many associations: index to one side is stored in a column in the many table as a foreign key.
  2. Many to many associations: need a cross reference table containing indices to both linked tables as foreign keys.

Object model: unique id implied.

Relational model: unique id must be explicit.

An Introduction to SQL

SELECT title FROM albums

Skip to JDBC ->

SQL commands

There are essentially only five SQL commands:

CREATE

CREATE TABLE TABLE_NAME (
	column_name column_type column_modifiers,
	...,
	column_name column_type column_modifiers)

CREATE Musicians

CREATE TABLE musicians (
	musician_id INT PRIMARY KEY,
	last_name CHAR(40),
	first_name CHAR(40),
	nickname CHAR(40))

CREATE (2)

INSERT

INSERT INTO TABLE_NAME (column_name, ..., column_name) VALUES (VALUE, ..., VALUE)
INSERT INTO musicians (musician_id, last_name, first_name, nickname)VALUES (2, 'Lydon', 'John', 'Johnny Rotten')

UPDATE

UPDATE TABLE_NAME 
SET column_name = VALUE,
    ...,
    column_name = VALUE
WHERE column_name = VALUE

UPDATE Examples

UPDATE albums 
SET YEAR = 1994 
WHERE album_id = 4

* Can be used to update several records at once:

UPDATE albums 
SET category = 'old music' 
WHERE YEAR < 1980

DELETE

DELETE FROM TABLE_NAME 
WHERE column_name = VALUE
DELETE FROM albums 
WHERE album_id = 4

SELECT

SELECT column_name, ..., column_name FROM TABLE_NAME 
WHERE column_name = VALUE
SELECT title FROM albums 
WHERE category='industrial'

Query By Example

Joins and …

SELECT bands.band_name FROM bands.albums 
WHERE albums.category='alternative' 
AND bands.band_id = albums.artist

… Sub-queries

SELECT title
FROM albums
WHERE artist IN	( 
  SELECT bands.band_id
  	  FROM bands, band_musicians
  	   WHERE band_musicians.musician_id = 2
  	     AND bands.band_id = band_musicians.band_id )

Lecture Contents

The Trouble with Databases

A Word about SQL and Portability

Design for Portability

What is JDBC?

A single API for database access:

SQL-level API

Based on existing APIs

Designed for Simplicity

The Structure of JDBC

The Structure of JDBC

Basic Classes and Interfaces of the JDBC API

Basic Classes and Interfaces of the JDBC API

Databases and Drivers

JDBC Driver Managers

Database URL

String dbUrl = "jdbc:odbc:CDs";  
jdbc:rmi://192.168.170.27:1099/jdbc:cloudscape:db 

Making a Connection

Find CDs for a party

See notes for listing.


1|Example 1: Database lookup (at-m42/Examples/lecture14/Lookup.java)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture14/Lookup.java

… define db attributes

static final String DB = "jdbc:derby:CDs";
static final String USER = "";
static final String PASSWORD = "";
static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";

… load the driver

Class.forName(DRIVER);

… connect to database

Connection c = DriverManager.getConnection(DB, USER, PASSSWORD);

… create a "statement" object

Statement s = c.createStatement();

… execute query and return results

// SQL query
String QUERY = "SELECT albums.title, bands.band_name, albums.year\n"
                + "  FROM bands INNER JOIN albums ON \n"
                + "     bands.band_id = albums.artist \n"
                + "  WHERE (((albums.category)='" + args[0] + "'))"
// SQL code:
ResultSet r = s.executeQuery(QUERY);

… process results

while (r.next()) {
    // Capitalization doesn't matter:
    System.out.println("Have a result!");
    System.out.println(r.getString("Title") + " by "
        + r.getString("bAND_NAME") + " released in "
        + r.getString("YEAR") + ".");
}

… close down connection and clean up

s.close();

Simplified Queries with Groovy

1|Example 2; Database lookup in Groovy (at-m42/Lectures/lecture14/Lookup.groovy)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture14/Lookup.groovy

As with other examples we've seen in this course, the designers of Groovy have created a JDBC API that further simplifies the interaction with a JDBC-supported database (and as we'll see, takes this even further in the Grails framework).

In this example we note immediately that the opening of a connection to a database is achieved in a single factory method def sql = Sql.newInstance(DB, USER, PASSWORD, DRIVER). Once we have the Sql object, we can use the eachRow method, which takes a closure, to process each row. Note also, that the results are returned as a Map, so we can refer to each field as r.band_name (or if you prefer r['band_name'] rather than the more long-winded r.getString("bAND_NAME")). Also, because Groovy is a dynamic language, we need not know, nor care, what the type of the field represents.

Further more, the use of multi-line strings simplifies the creation of queries, and because String interpretation works, queries can easily be made programmatic.

SQL Data-types and Java Data-types

Java TypeSQL Types (from java.sql.Types)
booleanBIT
byteTINYINT
shortSMALLINT
intINTEGER
longBIGINT
floatREAL
doubleDOUBLE
java.Math.BigDecimalNUMERIC
java.lang.StringVARCHAR or LONGVARCHAR

SQL Data-types and Java Data-types (2)

Java TypeSQL Types (from java.sql.Types)
byte[]VARBINARY or LONGVARBINARY
java.sql.DateDATE
java.sql.TimeTIME
java.sql.TimestampTIMESTAMP
java.sql.BlobBLOB (SQL3 datatype)
java.sql.ClobCLOB (SQL3 datatype)
java.sql.ArrayARRAY (SQL3 datatype)
java.sql.RefREF (SQL3 datatype)
java.sql.StructSTRUCT (SQL3 datatype)

What else does JDBC provide?

Transaction Logic (1)

Transaction Logic (2)

Lecture Contents

Immortal Objects

Persistence is Last Step in a Transaction

Component Transaction and Persistence Transaction

Persistence transaction

Lecture Contents

Persistence Patterns: Transaction script

In many applications it is natural to work directly with the relational model, issuing SQL queries and parsing result sets.

Persistence Patterns: ORM

Another scenario is that you have simple queries returning small sets of rows (often in a single table), which receive selective updates.

General term for this pattern is Object-Relational Mapping (ORM)

Patterns for ORM Strategies

Persistence Frameworks


Reese (see Recommended Reading) gives an extended example of the development of a persistence framework.

The most widely used persistence frameworks are:

The Object/Relational Impedance Mismatch

Some Issues that the Developers of an ORM Have to be Aware Of

Choosing a Persistence Strategy (1)

Choosing a Persistence Strategy (2)

Choosing a Persistence Strategy (3)

ORM can be of benefit if:

Lecture Contents

Other Forms of Enterprise Integration

—-

Some examples of enterprise information systems are:

Lecture Summary


Home | Previous Lecture | Lectures | Next Lecture

1)
All patterns discussed in this lecture are from Patterns of Enterprise Application Architecture. See Recommended Reading for bibliographic details.