© D. Wong 2003 1 Indexes JDBC JDBC in J2EE (Java 2 Enterprise Edition)
-
Upload
helena-bennett -
Category
Documents
-
view
216 -
download
0
Transcript of © D. Wong 2003 1 Indexes JDBC JDBC in J2EE (Java 2 Enterprise Edition)
11 © D. Wong 2003© D. Wong 2003
IndexesIndexes
JDBCJDBC
JDBC in J2EE (Java 2 Enterprise Edition)JDBC in J2EE (Java 2 Enterprise Edition)
22 © D. Wong 2003© D. Wong 2003
IndexesIndexes
An index on an attribute A is a data structure to An index on an attribute A is a data structure to improve query performance efficiency improve query performance efficiency
Reason: not efficient to scan all tuples (for large Reason: not efficient to scan all tuples (for large relations) in order to find the few that meet a relations) in order to find the few that meet a given conditiongiven condition
E.g. E.g. SELECT * FROM MovieSELECT * FROM Movie
WHERE studioName = ‘Disney’ AND WHERE studioName = ‘Disney’ AND year = 1990;year = 1990;
Not part of SQL standardNot part of SQL standard
33 © D. Wong 2003© D. Wong 2003
Indexes Typical SyntaxIndexes Typical Syntax
To create indexTo create index
CREATE INDEX indexName ON R(A1,…An)CREATE INDEX indexName ON R(A1,…An)
E.g. E.g.
1.1. CREATE INDEX YearIndex ON Movie(year);CREATE INDEX YearIndex ON Movie(year);
2.2. CREATE INDEX KeyIndex ON Movie(title, year);CREATE INDEX KeyIndex ON Movie(title, year);
Delete Index Delete Index
DELETE INDEX yearIndex;DELETE INDEX yearIndex;
44 © D. Wong 2003© D. Wong 2003
Selection of IndexesSelection of Indexes
Index design requires an estimate of the typical Index design requires an estimate of the typical mix of queries and other operations on the dbmix of queries and other operations on the db
Example of good use of indexes:Example of good use of indexes:
1.1. An attribute frequently compared to constant An attribute frequently compared to constant in a where clause of a queryin a where clause of a query
2.2. Attribute that appear frequently in join Attribute that appear frequently in join operationsoperations
e.g. SELECT name FROM Movie, MovieExece.g. SELECT name FROM Movie, MovieExec
WHERE title = ‘status’ AND producerC# WHERE title = ‘status’ AND producerC# = cert#;= cert#;
55 © D. Wong 2003© D. Wong 2003
Decision factorsDecision factors
Important to strike a balance.Important to strike a balance.
Factors:Factors:
1.1. Given attribute A, and index on A will:Given attribute A, and index on A will:
– Greatly speed up queries with a condition Greatly speed up queries with a condition on that attributeon that attribute
– May speed up joins involving AMay speed up joins involving A
2.2. Index make insertion, deletion, and updates Index make insertion, deletion, and updates more complex and time-consumingmore complex and time-consuming
66 © D. Wong 2003© D. Wong 2003
Indexes (continued)Indexes (continued)
Techniques to execute SQL queries are intimately Techniques to execute SQL queries are intimately associated with storage structures. Typically, a associated with storage structures. Typically, a relation is stored in many disk blocks.relation is stored in many disk blocks.
An index is an auxiliary structure, perhaps stored An index is an auxiliary structure, perhaps stored in a separate file, that support fast access to the in a separate file, that support fast access to the rows of a table.rows of a table.
Main cost of a query or modification is I/O:Main cost of a query or modification is I/O:
No. of disk blocks to be read into memory and No. of disk blocks to be read into memory and write onto diskwrite onto disk
77 © D. Wong 2003© D. Wong 2003
Index Selection ExampleIndex Selection Example
Given Relation: StarsIn(movieTitle, movieYear, starName)Given Relation: StarsIn(movieTitle, movieYear, starName)
3 operations to perform:3 operations to perform:
1.1. Q1: select movieTitle, movieYear From StarsIn Q1: select movieTitle, movieYear From StarsIn where starName = s; where starName = s;
2.2. Q2: select starName from StarsIn where Q2: select starName from StarsIn where movieTitle = t and movieYear = y;movieTitle = t and movieYear = y;
3.3. I: insert into StarsIn values(t, y, s);I: insert into StarsIn values(t, y, s);
where s, t, y are some constantswhere s, t, y are some constants
88 © D. Wong 2003© D. Wong 2003
Example's assumptionsExample's assumptions
1.1. Cost for examining 1 disk block = 1 unitCost for examining 1 disk block = 1 unit
2.2. StarsIn is stored in 10 disk blocksStarsIn is stored in 10 disk blocks
3.3. Average no. of stars in a movie = 3Average no. of stars in a movie = 3
4.4. Average no. of movies that a star appeared in = 3Average no. of movies that a star appeared in = 3
5.5. Tuples for a given star or movie are likely to be Tuples for a given star or movie are likely to be spread over the 10 disk blocks of StarsInspread over the 10 disk blocks of StarsIn
6.6. One disk access is needed to read a block of the One disk access is needed to read a block of the index every time when the index is used to locate index every time when the index is used to locate tuples with a given value for the indexd tuples with a given value for the indexd attribute(s)attribute(s)
99 © D. Wong 2003© D. Wong 2003
Example's Estimated Cost of actionsExample's Estimated Cost of actions
ActionAction No IndexNo Index Star IndexStar Index Movie IndexMovie Index Both IndexesBoth Indexes
Q1Q1 1010 44 1010 44
Q2Q2 1010 1010 44 44
II 22 44 44 66
Cost of 3 Cost of 3 actionsactions
2+8p2+8p11+8p+8p22 4+6p4+6p22 4+6p4+6p11 6-2p6-2p11-2p-2p22
Star index is an index on StarName, Movie index is an index on MovieTitle and movieYear.The numbers in rows 2-5 of the table are no. of disk accesses for the action.
Costs associated with the three actions, as a function of which indexes are selected (Ref. Fig. 6.17 2nd ed.)
1010 © D. Wong 2003© D. Wong 2003
Example's usage scenariosExample's usage scenarios
The fraction of the time to do Q1 = p1, Q2 = p2, The fraction of the time to do Q1 = p1, Q2 = p2, I=1-p1-p2I=1-p1-p2
Consider:Consider:
– Case 1: p1 = p2 = 0.1Case 1: p1 = p2 = 0.1
– Case 2: p1 = p2 = 0.4Case 2: p1 = p2 = 0.4
– Case 3: p1=0.5, p2=0.1Case 3: p1=0.5, p2=0.1
What is the best index strategy for each case?What is the best index strategy for each case? Create only the index that helps the most Create only the index that helps the most
frequently used query type (e.g. query about stars frequently used query type (e.g. query about stars => create Star index)=> create Star index)
1111 © D. Wong 2003© D. Wong 2003
JDBC (Java DataBase Connectivity)JDBC (Java DataBase Connectivity)
An API to the database driver managerAn API to the database driver manager
Provides call-level interface for the execution of Provides call-level interface for the execution of SQL statements from a Java language programSQL statements from a Java language program
Developed by SUN MicrosystemsDeveloped by SUN Microsystems
An integral part of the Java languageAn integral part of the Java language
Java applications use the JDBC dialect of SQL, Java applications use the JDBC dialect of SQL, independent of the DBMS usedindependent of the DBMS used
Support applications to request information about Support applications to request information about the schema from the DBMS at run time.the schema from the DBMS at run time.
1212 © D. Wong 2003© D. Wong 2003
JDBC Interaction with SQL DBJDBC Interaction with SQL DB
1.1. Make connection to the databaseMake connection to the database
2.2. Create SQL statementCreate SQL statement
3.3. Execute the SQL statementExecute the SQL statement
4.4. Result table from the SQL "select" statement is Result table from the SQL "select" statement is returned as a Java object. JDBC provide returned as a Java object. JDBC provide methods to access the rows and columns.methods to access the rows and columns.
5.5. SQL statements return simple integer results SQL statements return simple integer results that represent the number of affected rows (e.g. that represent the number of affected rows (e.g. insert)insert)
OR
1313 © D. Wong 2003© D. Wong 2003
Connecting to a db through JDBCConnecting to a db through JDBC
Application
Driver 1
Driver 2
Driver 3DBMS server
Driver Manager
JDBC Modules
1414 © D. Wong 2003© D. Wong 2003
JDBC - java.sql packageJDBC - java.sql package
Defines a collection of interfaces and classes that allow Defines a collection of interfaces and classes that allow programs to interact with db.programs to interact with db.
Interfaces for primary SQL execution:Interfaces for primary SQL execution:– Driver: supports data connection creationDriver: supports data connection creation
– Connection: represents connection between a java client Connection: represents connection between a java client and and SQL database serverand and SQL database server
– Statement: includes methods for executing text queriesStatement: includes methods for executing text queries
– PreparedStatement: represents a precompiled and stored PreparedStatement: represents a precompiled and stored queryquery
– CallableStatement: used to execute SQL stored proceduresCallableStatement: used to execute SQL stored procedures
– ResultlSet: contains the results of a queryResultlSet: contains the results of a query
– ResultSetMetaData: information about a ResultSet, ResultSetMetaData: information about a ResultSet, including the attribute names and typesincluding the attribute names and types
1515 © D. Wong 2003© D. Wong 2003
Client-server ArchitecturesClient-server Architectures
User Interface / Application
User Interface / Application
Middleware
Application
Database Server
Database Server
User and Application tier
Middle tier
Database Server tier
1616 © D. Wong 2003© D. Wong 2003
JDBC in J2EEJDBC in J2EE
J2EE – Java 2 Enterprise Edition, a middle layer server
Connection to DBMS using JDBC (e.g. Cloudscape, Oracle, MS SQL)
J2EE Platform – services and architecture
Enterprise JavaBeans (EJB)
– Session Beans vs. Entity Beans
EJB access to databases using JDBC
– Database connection
– Persistence management (Entity Bean e.g.)
– Transaction management (Session Bean e.g.)
1717 © D. Wong 2003© D. Wong 2003
J2EE ServicesJ2EE Services
HTTP - enables Web browsers to access servlets and JavaServer PagesTM (JSP) files
EJB - allows clients to invoke methods on enterprise beans
Authentication - enforces security by requiring users to log in
Naming and Directory - allows programs to locate services and components through the Java Naming and Directory InterfaceTM (JNDI) API
1818 © D. Wong 2003© D. Wong 2003
J2EE ArchitectureJ2EE Architecture
Ref. JavaTM 2 Enterprise Edition Developer's Guide, Figure 1-2
1919 © D. Wong 2003© D. Wong 2003
Enterprise JavaBeans (EJB)Enterprise JavaBeans (EJB)
Server-side Java components
Contain the business logic of enterprise application
Support database access
Transactional
Multi-user secure
Managed by the EJB container
Prohibited from a set of operations
2020 © D. Wong 2003© D. Wong 2003
Session Bean vs. Entity BeanSession Bean vs. Entity Bean
Session BeanSession Bean Entity BeanEntity Bean
PurposePurpose Performs a task for a Performs a task for a clientclient
Represents a business Represents a business entity object that exists in entity object that exists in persistent storage. persistent storage.
Shared Shared AccessAccess
May have one client.May have one client. May be shared by multiple May be shared by multiple clients.clients.
PersistencePersistence Not persistent. Not persistent. Persistent. Entity state Persistent. Entity state remains in a database. remains in a database.
Ref. JavaTM 2 Enterprise Edition Developer's Guide, Table 1-1
2121 © 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.
2222 © 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
2323 © 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);
2424 © D. Wong 2003© D. Wong 2003
Specifying JNDI name for deployment Step 1: Enter the code name
2525 © D. Wong 2003© D. Wong 2003
Step 2: Map the coded name to the JNDI name
2626 © 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!)
2727 © 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
2828 © D. Wong 2003© D. Wong 2003
2929 © D. Wong 2003© D. Wong 2003
3030 © D. Wong 2003© D. Wong 2003