32
CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak www.cs.sjsu.edu/~mak

CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak

Embed Size (px)

Citation preview

CS 157B: Database Management Systems IIJanuary 28 Class Meeting

Department of Computer ScienceSan Jose State University

Spring 2013Instructor: Ron Mak

www.cs.sjsu.edu/~mak

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

2

Form Project Teams

3 students each. Pick a team name.

Each team member will get the same score for each team project.

Teams will last the entire semester. Choose your team members wisely!

Someone from each team send me: Your team name Name and email address of each team member

_

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

3

MySQL

Popular open-source relational database management system (RDBMS).

The M in LAMP (Linux+Apache+MySQL+PHP) or Perl or Python

Now part of Oracle. Download from http://www.mysql.org/

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

4

The MySQL Workbench MySQL Workbench features

Manage databases and database connections. Edit, execute, and save SQL scripts.

Forward- and reverse-engineering Generate an ER diagram from an existing database. Manually create an ER diagram. Automatically generate a database from the diagram.

Replaces the older MySQL Administrator and MySQL Query Browser tools.

Open-source version of some very expensive commercial database design and management tools (such as ERWin Data Modeler). Download from http://dev.mysql.com/downloads/

Demo

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

5

Take roll

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

6

JDBC

Use the JDBC (Java Database Connectivity) API in the java.sql package to make your Java program communicate with a database.

Requires the use of a database driver.

For MySQL, download Connector/J fromhttp://dev.mysql.com/downloads/connector/j/

Jar file: mysql-connector-java-5.1.12-bin.jar

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

7

JDBC Connection Make a connection to the database using a

URL, username, and password.

Example:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;import java.sql.ResultSet; import java.sql.SQLException;

...

private static String DB_URL = "jdbc:mysql://localhost:3306/school";private static String USERNAME = "root";private static String PASSWORD = "sesame";

...

Connection conn = DriverManager.getConnection( DB_URL, USERNAME, PASSWORD);

Different URL formatfor an Oracle database.

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

8

JDBC Query Create a statement and then generate a result set

by executing a query.

Example:

String QUERY = "SELECT * FROM teacher";

Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(QUERY);

_

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

9

Iterate over a JDBC Result Set

Example:ResultSet rs = stmt.executeQuery(QUERY);

int id;String lastName;String firstName;

while (rs.next()) { id = rs.getInt("id"); lastName = rs.getString("last"); firstName = rs.getString("first"); ...}

Id Last First

7003 Rogers Tom

7008 Thompson Art

7012 Lane John

7051 Flynn Mabel

Teacher

Instead of the database field names, you can use 1, 2, 3, ...

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

10

Object-Relational Mapping Create Java objects from relational database tables.

Example:

public class Teacher{ int id; String lastName; String firstName;}

...

while (rs.next()) { Teacher teacher = new Teacher(rs.getInt("id"), rs.getString("last"), rs.getString("first")); ...}

A better way is to use Hibernate to automate object-relational mapping between a Java program and a relational database.

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

11

SQL Query Example Who are John Lane’s students?

Id Last First

1001 Doe John

1005 Novak Tim

1009 Klein Leslie

1014 Jane Mary

1021 Smith Kim

Code Teacher_id Subject Room

908 7008 Data structures 114

926 7003 Java programming 101

931 7051 Compilers 222

951 7012 Software engineering 210

974 7012 Operating systems 109

Student_id Class_code

1001 926

1001 951

1001 908

1005 974

1005 908

1014 931

1021 926

1021 974

1021 931

SELECT student.first, student.last, subjectFROM student, teacher, class, student_classWHERE teacher.last = 'Lane' AND teacher.first = 'John'AND teacher_id = teacher.idAND code = class_code AND student.id = student_idORDER BY subject, student.last

+-------+-------+----------------------+| first | last | subject |+-------+-------+----------------------+| Tim | Novak | Operating systems || Kim | Smith | Operating systems || John | Doe | Software engineering |+-------+-------+----------------------+

Id Last First

7003 Rogers Tom

7008 Thompson Art

7012 Lane John

7051 Flynn Mabel

Teacher StudentClass

Student_Class

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

12

JDBC Prepared Statement

Putting a query statement in a loop is inefficient, because the database server has to reparse the statement and build an execution plan each time, even if the statement doesn’t change.

Use a prepared statement instead. Example:

String query = "SELECT student.first, student.last, subject " + "FROM student, teacher, class, student_class " +

"WHERE teacher.last = ? AND teacher.first = ? " + "AND teacher_id = teacher.id " + "AND code = class_code AND student.id = student_id " + "ORDER BY subject, student.last";

PreparedStatement ps = conn.prepareStatement(query);

Note the two ? parameters.

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

13

JDBC Prepared Statement

You can do repeated queries on different teachers by using a prepared statement and parameter substitution. Example:

for (Teacher teacher : teachers) { String lastName = teacher.getLastName(); String firstName = teacher.getFirstName();

ps.setString(1, lastName); ps.setString(2, firstName);

ResultSet rs = ps.executeQuery();

while (rs.next()) { ... }}

Count the ?’s from 1, not 0.

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

14

JDBC Result Set Metadata

Each result set has metadata that containsuseful information about the query.

number of columns column labels etc.

Example:

ResultSet rs = ps.getResultSet();ResultSetMetaData rsmd = rs.getMetaData();

...

int colCount = rsmd.getColumnCount();String label1 = rsmd.getColumnLabel(1);String label2 = rsmd.getColumnLabel(2);

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

15

Database Record Insert, Update, and Delete

There are SQL statements to insert, update, and delete records. Three separate examples:

INSERT INTO teacher (id, last, first)VALUES (7088, 'Mak', 'Ron'), (7090, 'Wilson', 'Brian')

UPDATE teacherSET first = 'Ronald'WHERE first = 'Ron'

DELETE FROM teacherWHERE id = 7090

JDBC API: Use the executeUpdate() method of a statement or a prepared statement object to modify the database (insert, update, or delete). The return value is the number of records that were affected.

This can updatemultiple records!

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

16

JDBC Example: Database Record Insert

Method executeUpdate() returns the number of records that were inserted._

String insert = "INSERT INTO teacher (id, last, first)" + "VALUES (7088, 'Mak', 'Ron'), " + " (7090, 'Wilson', 'Brian') ";

Statement stmt = conn.createStatement();int rowCount = stmt.executeUpdate(insert);

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

17

JDBC Example: Database Record Update

String update = "UPDATE teacher" + "SET first = 'Robert'" + "WHERE first LIKE= 'Ron%'";

rowCount = stmt.executeUpdate(update);

In any WHERE clause, LIKE allows wild cards in the string pattern. % matches zero or more characters.

'Ron%' matches 'Ron' and 'Ronald' _ matches any single character.

'_onald' matches 'Ronald' and 'Donald‘

Method executeUpdate() returns the number of records that were changed.

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

18

JDBC Example: Database Record Delete

Method executeUpdate() returns the number of records that were deleted._

String delete = "DELETE FROM teacher" + "WHERE first = 'Robert'";

rowCount = stmt.executeUpdate(delete);

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

19

Closing JDBC Objects

When you’re done with them, don’t forget to close your JDBC statement, prepared statement, and result set objects, and especially the database connection object. Examples:

stmt.close();ps.close();rs.close();conn.close();

Note that most JDBC API calls throw an exception if an error occurred, generally SQLException, which you’ll need to catch.

A database server cansupport only a limitednumber of connections.

Demo

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

20

Data Access Layer

Databases and SQL are extremely powerful. Let MySQL do what it’s good at doing,

and let Java do what it’s good at doing. For example, don’t write Java code to sort the records –

let the database do that!

Add a data access layer to your application. The data access layer contains all the JDBC API calls

and manages the database connection pool. Keep the rest of your application loosely-coupled

from the database code. With object-relational mapping, the rest of your application

deals only with objects, not result sets._

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

21

APPLICATION

Multilayered Application Architecture

Presentation Layer GUI Objects

Application LayerApplication Logic Objects

Data Access LayerFetch and Store Model Objects

Database

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

22

Shortcomings of JDBC

Java programmers must understandrelational databases. The database is very visible. The Java programmer must know SQL.

JDBC is not object-oriented. A Java program accesses field values individually

from a result set. You need statements to create Java objects

from the result set values._

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

23

Object-Relational Mapping

Goal: Overcome the paradigm mismatch between relational data from an RDBMS and object-oriented programming.

Object-oriented languages such as Java would much rather deal with classes and objects. Java programmers do not want to write SQL. Java programmers do not want to want to deal

with database concepts such as one-to-many, one-to-many, many-to-many, etc.

Java programmers do not want to understand normalization._

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

24

Object-Relational Mapping

Solution: Add a layer of software between the database and the Java application that does object-relational mapping. Relational data being read from the database are

automatically converted to objects. Objects being persisted (saved) to the database are

automatically converted to relational data. The Java application manipulates objects (create, update,

search, delete) and these operations are automatically translated into the corresponding database operations.

Database platform independence.

The Java programmer can mostly forget that there is an underlying database._

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

25

Hibernate

A very popular open-source object-relational persistence and query service for Java. Download from http://www.hibernate.org/

Replace the JDBC API with the Hibernate API.

Java annotations describe in detail the mapping between the Java classes and the relational database tables. _

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

26

Hibernate: Student

Note the annotations. Provide metadata for

the Java compiler and the Java run time.

@Entitypublic class Student { private long id; private String firstName; private String lastName; public Student() {} public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } ...}

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

27

Hibernate: Student

@Entitypublic class Student { ... @Id @GeneratedValue @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name="first_name") public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; } @Column(name="last_name") public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; } ...}

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

28

Hibernate: Student

Import Java packages: Hibernate Hibernate annotations Log4J

package schooldemo;

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Column;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.AnnotationConfiguration;import org.hibernate.tool.hbm2ddl.SchemaExport;

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

29

Hibernate: Student

Main method (for testing)

public static void main(String args[]){ // Configure Hibernate and add the Student class. AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Student.class); config.configure(); // Create the database table. (new SchemaExport(config)).create(true, true); // Create a session. SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); ...}

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

30

Hibernate: Studentpublic static void main(String args[]){ ... // Create a session. SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); // Load the Student table in a transaction. Transaction tx = session.beginTransaction(); { session.save(new Student("Mary", "Jane")); session.save(new Student("Kim", "Smith")); session.save(new Student("John", "Doe")); session.save(new Student("Tim", "Novak")); session.save(new Student("Leslie", "Klein")); } tx.commit(); session.close();}

Main method

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

31

hibernate.cfg.xml

Hibernate configuration file Modify as necessary. Must be in your application’s classpath.

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration> <session-factory>

<!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/school_demo</property> <property name="connection.username">root</property> <property name="connection.password">sesame</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

<!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> </session-factory></hibernate-configuration>

Department of Computer ScienceSpring 2013: January 28

CS 157B: Database Management Systems II© R. Mak

32

log4j.properties

Just copy the sample file. Also must be in your classpath.

Demo