Quiz 1. Describe the similarities and differences of Tester class and GUI class 2. What is the function of GUI class? 3. What is the function of PD(problem domain) class? 4. How does a GUI class interact with PD class? 1/105 Introduction to Data Access Classes (Reference Chapter 7) 2
Topics Make objects persistent ( 持 久 ) How to create a DB and data table Design a data access class PD class Communicates with a data access class Use a relational database with Java 3/105 Making Objects Persistent Object persistence The capacity to store and retrieve information from files/database Using it When to store instances or their attributes values for future retrieval 4/105
Object Storage Object Storage namely Object serialization ( 序 列 化 ) To store and retrieve entire instances Advantage The object can be retrieved intact ( 完 好 无 损 ) It is not necessary to re-create the object 5/105 Attribute storage Attribute storage - Involves Writing attribute values to a file or database Retrieving attribute values from a file or database 6/105
Files a collection of data or information that has a name, called the filename stored on devices for Long-term storage Magnetic disks Optical disks Magnetic tapes Sequential and random access files 7/105 Data structure in a file File is a group of related records One field in each record is a record key Record key is a unique identifier for a record Sequential file Records stored in order by record key Data hierarchy 8/105
Files and data Streams Java views a file as a data stream In a program, we read information from an input stream and write information to an output stream An I/O stream is either a character stream, which deals with text data byte stream, which deal with image and sound data The data is coded using Unicode Unicode : 国 际 标 准 字 符 集 9/105 Buffering Improves performance of I/O Copies each output( 字 节 或 字 符 ) to a region of memory called a buffer Entire buffer output to disk at once One long disk access takes less time than many smaller ones ( 成 批 读 入 和 读 出, 高 速 缓 存 访 问, 效 率 比 较 高 ) BufferedOutputStream 类 能 够 在 内 存 里 为 输 出 文 件 建 立 一 个 缓 冲 区 BufferedInputStream buffers file input 10/105
Sequential Access File Is a Java File The files Can be byte or text Must start at the beginning and read it sequentially 顺 序 读 写 Can not jump to a specific record number Can not insert or delete a specific record Difficult to update a sequential-access file Entire file must be rewritten to change one field 11/105 Sequential Access File cont. How to read and write Using method readline() in BufferedReader claas Using method println() in PrintStream class java.io.reader java.io.bufferedreader 12/105
Random-access access files Access individual records directly and quickly Use fixed length for every record Easy to calculate record locations Insert records without destroying ( 破 坏 )other data in file Reads or writes data in spot ( 点 )specified by file-position pointer Manipulates( 操 纵 )all data as primitive( 基 本 ) types Normally writes one object at a time to file 13/105 Selected Classes in the java.io package File class File 类 的 方 法 主 要 用 于 获 取 文 件 本 身 的 一 些 信 息 例 如, 文 件 所 在 的 目 录 文 件 的 长 度 等 Constructor File(String filename), 其 中 参 数 filename 是 文 件 名 File(String directorypath, String filename), 其 中 参 数 directorypath 是 文 件 的 路 径 Methods String getname(): 获 取 文 件 的 名 字 boolean exists(): 判 断 文 件 是 否 存 在 long length(): 获 取 文 件 的 长 度 ( 单 位 是 字 节 ) boolean isfile(): 判 断 是 否 是 一 个 文 件 14/105
Cont. FileInputStream class( 字 节 输 入 流 类 ) 可 实 现 以 字 节 为 单 位 顺 序 读 取 外 存 文 件 的 内 容 到 内 存,( 用 于 读 取 诸 如 图 像 数 据 之 类 的 原 始 字 节 流 ) 所 用 的 method 是 read 关 闭 字 节 输 入 流 用 的 method 是 close Constructor FileInputStream (String filename), 其 中 参 数 filename 是 文 件 名 ( 包 括 路 径 ) 用 给 定 的 文 件 名 创 建 一 个 FileInputStream 实 例, 用 来 打 开 一 个 到 达 该 文 件 的 输 入 流, 这 个 文 件 就 是 源 ( 在 外 存 上 ) FileInputStream (File f), 其 中 参 数 f 是 指 定 的 一 个 文 件 用 来 指 定 要 打 开 那 个 文 件 15/105 Cont. FileOutputStream class( 字 节 输 出 流 类 ) 用 于 实 现 以 字 节 为 单 位 顺 序 写 数 据 到 文 件, 所 用 的 方 法 是 write, 关 闭 字 节 输 出 流 使 用 方 法 close 创 建 FileOutputStream 类 的 实 例 也 称 为 创 建 文 件 字 节 输 出 流 Constructor FileOutputStream (String filename), 其 中 参 数 filename 是 文 件 名 FileOutputStream (File f), 其 中 参 数 f 是 指 定 的 一 个 文 件 16/105
Cont. FileReader class( 字 符 输 入 流 类 ) 用 于 实 现 以 字 符 为 单 位 从 文 件 中 顺 序 输 入 字 符 流 到 内 存, 使 用 的 方 法 是 read, 关 闭 字 符 输 入 流 使 用 方 法 close Constructor FileReader (String filename) FileReader (File filename) 17/105 Cont. FileWriter class( 字 符 输 出 流 类 ) 支 持 以 字 符 为 单 位 顺 序 的 将 字 符 流 输 出 到 文 件, 使 用 的 方 法 是 write 方 法, 关 闭 字 符 输 出 流 用 方 法 close Constructor FileWriter (String filename) FileWriter (File filename) 18/105
Cont. RandomAccessFile class( 随 机 访 问 类 ) 支 持 随 机 读 写 文 件 提 供 了 很 多 文 件 的 读 和 写 的 方 法, 例 如 : readline, writebytes 等 Constructor RandomAccessFile(String filename,string mode), 其 中 参 数 filename 是 文 件 名, 参 数 mode 可 能 的 形 式 是 r( 只 读 ) 或 rw( 可 读 写 ) RandomAccessFile(File filename,string mode), 其 中 参 数 filename 是 文 件 名, 参 数 mode 可 能 的 形 式 是 r( 只 读 ) 或 rw( 可 读 写 ) 19/105 Create a file and show some info 20/105
Read and write to sequence file 21/105 Read and write to Random-access access files RandomAccessFile 类 可 对 文 件 实 现 随 机 读 写 操 作, 即 可 以 随 机 地 读 取 一 个 文 件 中 指 定 位 置 的 记 录 和 写 记 录 到 文 件 指 定 的 位 置 为 方 便 随 机 读 写, 要 求 随 机 文 件 的 每 个 记 录 的 字 节 数 相 等 实 现 随 机 读 写 是 靠 随 机 文 件 流 的 位 置 指 针 定 位 的 RandomAccessFile 对 象 的 文 件 位 置 指 针 遵 循 下 面 的 规 则 : 新 建 RandomAccessFile 对 象 的 文 件 位 置 指 针 位 于 文 件 的 开 头 处 ; 每 次 读 写 操 作 之 后, 文 件 位 置 的 指 针 都 会 相 应 后 移 到 读 写 的 字 节 数 处 ; 可 以 通 过 getfilepointer 方 法 来 获 得 位 置 指 针 的 值, 通 过 seek 方 法 来 设 置 文 件 指 针 的 位 置 由 此 读 出 指 针 指 向 的 记 录 22/105
Example 7.5 将 若 干 个 学 生 的 信 息 存 入 到 文 本 文 件 students.txt 假 设 要 存 入 的 每 个 学 生 信 息 是 : 姓 名, 学 号, 每 一 个 学 生 的 信 息 是 一 个 记 录 然 后 按 规 定 的 顺 序 读 取 记 录 : 先 读 第 二 个 学 生 记 录, 再 读 第 一 个 学 生 记 录, 再 读 第 三 个 学 生 记 录 解 题 思 路 : 先 定 义 问 题 域 (PD) 类 Student; 然 后 编 写 一 个 主 动 类 ( 应 用 程 序 ), 能 随 机 读 写 学 生 记 录 23/105 (1) define Student class Student studentid name 24/105
(2) 编 写 一 个 能 随 机 读 写 3 个 学 生 的 记 录 的 程 序 TestRandomIO 先 创 建 3 个 Student 实 例, 然 后 写 学 生 记 录 到 文 件 student.txt, 再 随 机 读 入 注 意 每 个 记 录 的 长 度 应 相 等, 以 便 容 易 确 定 要 读 写 记 录 的 位 置 因 为 一 个 汉 字 两 个 字 节, 名 字 的 长 度 最 长 是 4 个 字, 8 个 字 节, 学 号 长 度 8 个 字 节 故 一 个 记 录 共 16 个 字 节 25/105 (3) TestRandomIO class 26/105
cont 27/105 cont 28/105
cont 29/105 Databases A database is a collection of data or information that is organized so that it can easily be accessed, managed, and updated. Databases management system (DBMS) Provide tools for organizing data into tables Such as MS SQL server, MS Access, Oracle 30/105
In a DBMS Table Relationship Databases Rows, columns Each column represents a field Each row represents a record Primary key: a field used to uniquely identify a record 31/105 Design Databases For example MS Access DB How to create, open and close a Database How to create data tables and close the data table How to modify data table Modify the design of a table add/delete a field How to input and modify data in a table. 32/105
Design Databases cont. Implementing the relationship between tables in DB 33/105 JDBC, ODBC, JdbcOdbcDriver Accessing a DBMS with Java, Need JDBC, ODBC and JdbcOdbcDriver JDBC (Java Database Connectivity) 它 是 一 个 应 用 程 序 接 口 (API), 通 过 它 可 访 问 各 种 关 系 数 据 库 JDBC 也 是 Java 核 心 类 库 的 一 部 分 JDBC 做 三 件 事 与 数 据 库 建 立 链 接 ; 发 送 SQL 语 句 ; 处 理 数 据 结 果 34/105
JDBC, ODBC, JdbcOdbcDriver cont. ODBC (Open Database Connectivity in a PC) provided by Microsoft ODBC 是 微 软 公 司 提 出 的 一 套 数 据 库 连 接 标 准, 它 和 JDBC 优 点 类 似, 主 要 是 为 了 设 置 数 据 库 连 接 接 口 的 统 一 ODBC can be used to access most databases (Microsoft SQL Server, Microsoft Access) 35/105 JDBC, ODBC, JdbcOdbcDriver cont. 应 用 程 序 要 访 问 一 个 数 据 库, 首 先 用 ODBC 管 理 器 为 数 据 库 注 册 一 个 数 据 源 名 字 (data source name) ODBC 管 理 器 根 据 数 据 源 提 供 的 数 据 库 位 置 ( 路 径 ) 数 据 库 类 型 及 ODBC 驱 动 程 序 等 信 息, 建 立 起 ODBC 与 具 体 数 据 库 的 联 系 只 要 应 用 程 序 将 数 据 源 的 名 称 (DSN) 提 供 给 ODBC,ODBC 就 能 建 立 起 与 相 应 数 据 库 的 连 接 How to create a DSN(data source name)? 36/105
JDBC, ODBC, JdbcOdbcDriver cont. JdbcOdbcDriver: a driver( 驱 动 程 序 ): 要 通 过 JDBC 访 问 ( 存 取 ) 某 一 特 定 的 数 据 库, 必 须 有 相 应 的 JDBC driver JDBC (Sun ), ODBC(MS) 不 同 公 司 的 产 品 JDBC --- JdbcOdbcDriver --- ODBC --- DB 37/105 Introduction to SQL Structured Query Language (SQL) A standardized language used to manage and query relational databases ( 在 MS Access 上 讲 解 各 语 句 的 执 行, 在 Design view 中 选 SQL view) 38/105
Introduction to SQL cont. Basic SQL statements query and modify tables and columns SELECT Statement - query tables and views in the database INSERT Statement - add rows to tables UPDATE Statement - modify columns in table rows DELETE Statement - remove rows from tables 39/105 SELECT Statement Queries data from tables in the database Basic format SELECT column-list FROM table [WHERE (logical expression )] Example SELECT address, phone FROM customer WHERE name= JoAnn SELECT * FROM customer WHERE name= JoAnn OR name= Mike order by phone SELECT * FROM customer 40/105
INSERT Statement Add one row to a table Format INSERT INTO table [(column-list)] VALUES (valuelist) Example INSERT INTO customer VALUES ( Judy, Beijing, 67891234 ) INSERT INTO customer (name, phone) VALUES ( Judy, 67891234 ) 41/105 UPDATE Statement Modify columns in selected table rows Format UPDATE table-1 SET set-list [WHERE predicate] SET column-1 = value-1 [, column-2 = value-2]... Example UPDATE customer SET address= Wuhan, phone= 87542234 WHERE name= Judy 42/105
DELETE Statement Removes selected rows from a table Format DELETE FROM table-1 [WHERE predicate] Example DELETE FROM customer WHERE name= Judy 43/105 Selected classes c in java.sql 44/105
下 面 举 例 说 明 以 上 各 类 的 使 用 编 写 一 个 TestJDBC 程 序, 查 询 数 据 库 phonebook 中 联 系 人 的 信 息 45/105 TestJDBC class 46/105
cont. 47/105 cont. 48/105
Data access Application programming model User < > GUI class < >PD class < >DA class< >DB 49/105 Designing a Data Access Class Purpose of a DA class To provide methods that store and retrieve data to files or database Reasons 1. Data input and output code are isolated from other classes Can dramatically reduce maintenance 2. Separate classes for each tier make deployment easier in a client-server environment GUI, PD, and DA functions may reside on multiple machines at various sites 例 : 买 卖 股 票 系 统 50/105
Designing a Data Access Class cont. A separate DA class is written for a PD class ( or one DA class for PD classes) DA methods are invoked only by the PD class A DA class diagram 51/105 Example Define a class User s DA class: UserDA Assume UserDA class attributes userid name password, Methods initialize,terminate,add,update, delete and find 52/105
cont Solution Steps: 1. define User class (see P178, 为 测 试 UserDA 所 使 用,) 2. [create Database and table usert (see P179, 为 测 试 UserDA 所 使 用 ) ] 3. define UserDA class 4. define NotFoundException class (used for UserDA) 5. define DuplicateException class (used for UserDA) 6. Code Tester class 53/105 Designing UserDA class userda class s methods addnew method: public static void add(user auser ) throws DuplicateException { } update method: public static void update(user auser ) throws NotFoundException { } delete method: public static void delete (User auser ) [ throws NotFoundException] { } find method: public static User find (String userid) throws NotFoundException { } 54/105
Designing UserDA class class cont. Additional methods Initialize: read data from a file or create a connection to DB public static void initialize(){ } Terminate: write data to a file or close the connection public static void terminate(){ } 55/105 Exception handler classes NotFoundException (used for finding data) public class NotFoundException extends Exception { } DuplicateException (used for add data) public class DuplicateException extends Exception { } 每 个 方 法 中 的 语 句 根 据 存 储 文 件 类 型 不 同 而 不 同 56/105
Implementing DA class with DB add method uses the SQL INSERT INTO statement to add a new user s record to the database update method uses SQL UPDATE statement to change the contents of one or more fields in a user s record 57/105 Implementing DA class with DB cont. Delete method executes the SQL DELETE statement DELETE statement specifies the key value of the customer to be deleted find method uses the SQL SELECT statement to Retrieve a specific user s record from the database 58/105
Example: Implementing UserDA class with DB DSN ( 数 据 源 名 字 ) 59/105 UserDA class Cont. 60/105
UserDA class Cont. 61/105 UserDA class Cont. 62/105
UserDA class Cont. 63/105 UserDA class Cont. 64/105
UserDA class Cont. 65/105 Defining DuplicateException class public class DuplicateException extends Exception{ //constructor public DuplicateException(String message){ super(message); } } 66/105
Defining NotFoundException class public class NotFoundException extends Exception{ //constructor public NotFoundException(String message){ super(message); } } 67/105 Testing interaction of UserDA class and DB Create two User s instance Test each method in UserDA 68/105
TesterUserDA class 69/105 cont 70/105
cont 71/105 cont 72/105
PD Class Communicate with a DA Class 从 类 图 来 看 两 者 没 有 区 别 73/105 Modifying PD class:user class User class ( is a PD class) methods in UserDA also includes these methods for invoking initialize Terminate find add update delete static methods instance methods 74/105
Modifying PD class:user class Adding methods that invoke UserDA methods 75/105 cont 没 有 参 数 代 表 user 实 例 76/105
Testing interaction about User class and UserDA 书 中 UserDA change to User 77/105 cont 78/105
cont 79/105 较 复 杂 的 数 据 库 访 问 的 实 现 --- 一 对 一 关 系 的 数 据 表 的 访 问 例 : 现 假 设 要 对 学 生 基 本 信 息 及 住 址 信 息 进 行 管 理, 如 对 这 些 信 息 添 加 修 改 删 除 和 查 询 解 题 思 路 : 首 先 找 出 问 题 域 类 画 出 类 图, 并 给 出 各 类 的 详 细 说 明 据 此 设 计 相 应 的 数 据 库 表 ; 然 后 再 定 义 PD classes 和 相 应 的 DA class; 最 后 编 写 测 试 程 序 ( 或 定 义 GUI 类 ) 80/105
(1)) 问 题 域 类 图 单 向 关 联 81/105 (2)) 创 建 数 据 库 及 数 据 表 82/105
(3)Define PD Class Student class (see P189) 5 attributes (including Address reference) 1 constructor 5 getters, 5 setters? 1 getdetails 3 static methods Initialize, terminate, find 3 instance methods add, update, delete 83/105 (3)Define PD Class cont. Address class (p190) 5 attributes (don t need Student reference?) 1 constructor 5 getters, 5 setters 1getDetails 84/105
(4)Define DA Class- StudentDA StudentDA class (p191) 4 attributes 6 methods 85/105 Defined StudentDA class 86/105
cont. 87/105 cont. 88/105
cont. 89/105 cont. 90/105
cont. If need to update the address of the student, how? 91/105 cont. 92/105
cont. public Student(String studentid,string name,string phone,string email, Address address) { setname( name) ; setstudentid(studentid); setphone( phone); setemail(email); setaddress(address); } 通 过 Student s constructor 中 setaddress() 完 成 关 联 93/105 P194-195 (5)Code Tester class 94/105
较 复 杂 的 数 据 库 访 问 的 实 现 --- 一 对 多 关 系 的 数 据 表 的 访 问 例 : 现 假 设 要 查 询 手 机 联 系 人 的 信 息, 包 括 姓 名 和 电 话 号 码 解 题 思 路 : 首 先 找 出 问 题 域 类 画 出 类 图, 并 给 出 各 类 的 详 细 说 明 据 此 设 计 相 应 的 数 据 库 表 ; 然 后 再 定 义 问 题 域 类 和 相 应 的 数 据 访 问 类 ; 最 后 编 写 测 试 程 序 95/105 (1)) 问 题 域 类 图 96/105
(2)) 创 建 数 据 库 及 数 据 表 97/105 (3)Define PD Class Contact class (session 5.5.3) Phone class 在 本 例 中 主 要 介 绍 ContactDA 类 中 find 方 法 和 getall 方 法 如 何 编 写 Declaring ContactDA class global variables 98/105
(4)Define ContactDA Class find method (p179) 控 制 重 复 数 据 只 显 示 一 次 99/105 Cont. (4)Define ContactDA Class 建 立 关 联 关 系 (see p127) 100/105
find() 控 制 流 程 如 下 101/105 (4)Define ContactDA Class getall method 102/105
Cont. getall method freqcontact, 103/105 Cont. 104/105
getall() 工 作 流 程 : 105/105 Summary Object persistence: storing instance data for future retrieval Persistence can be achieved by storing either attribute values or entire instances A data access (DA) class provides methods that store and retrieve data into tables Methods of a DA class are invoked only by the methods of the corresponding PD class Methods of a DA class: find, addnew, update, delete, getall, initialize, and terminate 106/105
Summary Java stream approach to I/O views data input and output as a flow of bytes Persistence can be achieved using sequential files, Random file, object serialization, or relational databases A relational database is used to organize data In a relational database, each column represents a field and each row represents a record SQL is a popular, standard language used to access relational databases 107/105 P200 9,10,11,12,17 第 3 个 实 验 Practices 108/105