object serialization and persistence n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Object Serialization and Persistence PowerPoint Presentation
Download Presentation
Object Serialization and Persistence

Loading in 2 Seconds...

play fullscreen
1 / 95

Object Serialization and Persistence - PowerPoint PPT Presentation


  • 89 Views
  • Uploaded on

Object Serialization and Persistence. 对象序列化和持久化. 摘要. 对象序列化 对象持久化 Language level Databases Hibernate. 摘要. 对象序列化 对象持久化 Language level Databases Hibernate. 摘要. 对象序列化 对象持久化 Language level Databases Hibernate. Object Serialization. Why What How. Java Object Serialization -- Why.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Object Serialization and Persistence' - zofia


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
object serialization and persistence
Object Serialization and Persistence

对象序列化和持久化

Institute of Computer Software

Nanjing University

slide2
摘要
  • 对象序列化
  • 对象持久化
    • Language level
    • Databases
  • Hibernate

Institute of Computer Software

Nanjing University

slide3
摘要
  • 对象序列化
  • 对象持久化
    • Language level
    • Databases
  • Hibernate

Institute of Computer Software

Nanjing University

slide4
摘要
  • 对象序列化
  • 对象持久化
    • Language level
    • Databases
  • Hibernate

Institute of Computer Software

Nanjing University

object serialization
Object Serialization
  • Why
  • What
  • How

Institute of Computer Software

Nanjing University

java object serialization why
Java Object Serialization -- Why
  • Serialization is used for lightweight persistence and for communication via sockets or Remote Method Invocation (RMI).

Institute of Computer Software

Nanjing University

java object serialization example
Java Object Serialization -- Example

public class Client {

public static void main(String args[]) {

try { // Create a socket

Socket soc = new Socket(InetAddress.getLocalHost(), 8020); OutputStream o = soc.getOutputStream();

ObjectOutput s = new ObjectOutputStream(o); s.writeObject("Today's date");

s.writeObject(new Date());

s.flush();

s.close(); }

catch (Exception e) {

System.out.println(e.getMessage());

System.out.println("Error during serialization");

System.exit(1); }

}

}

Institute of Computer Software

Nanjing University

java object serialization example1
Java Object Serialization -- Example

public class Server {

public static void main(String args[]) {

ServerSocket ser = null; Socket soc = null; String str = null;

Date d = null;

try {

ser = new ServerSocket(8020);

soc = ser.accept();

InputStream o = soc.getInputStream();

ObjectInput s = new ObjectInputStream(o);

str = (String) s.readObject();

d = (Date) s.readObject();

s.close();

System.out.println(str); System.out.println(d);

} catch (Exception e) {

System.out.println(e.getMessage());

System.out.println("Error during serialization");

System.exit(1);

}

}

}

Institute of Computer Software

Nanjing University

java object serialization example2
Java Object Serialization -- Example
  • Writing to an object stream

// Serialize today's date to a file.

FileOutputStream f = new FileOutputStream("tmp");

ObjectOutput s = new ObjectOutputStream(f);

s.writeObject("Today");

s.writeObject(new Date());

s.flush();

Institute of Computer Software

Nanjing University

java object serialization example3
Java Object Serialization -- Example
  • Reading from an object stream

// Deserialize a string and date from a file.

FileInputStream in = new FileInputStream("tmp");

ObjectInputStream s = new ObjectInputStream(in);

String today = (String)s.readObject();

Date date = (Date)s.readObject();

Institute of Computer Software

Nanjing University

java object serialization what
Java Object Serialization -- What
  • Object Serialization extends the core Java Input/Output classes with support for objects.
  • Object Serialization supports the encoding of objects, and the objects reachable from them, into a stream of bytes; and it supports the complementary reconstruction of the object graph from the stream.

Institute of Computer Software

Nanjing University

java object serialization goal
Java Object Serialization -- Goal
  • Have a simple yet extensible mechanism.
  • Maintain the Java object type and safety properties in the serialized form.
  • Be extensible to support marshaling and unmarshaling as needed for remote objects.
  • Be extensible to support simple persistence of Java objects.
  • Require per class implementation only for customization.
  • Allow the object to define its external format.

Institute of Computer Software

Nanjing University

java object serialization how
Java Object Serialization -- How
  • Objects to be saved in the stream may support either the Serializable or the Externalizable interface.
    • For Serializable objects, the stream includes sufficient information to restore the fields in the stream to a compatible version of the class.
    • For Externalizable objects, the class is solely responsible for the external format of its contents.

Institute of Computer Software

Nanjing University

the serializable interface
The Serializable Interface
  • public interface java.io.Serializable { };
  • A Serializable class must do the following:
    • Implement the java.io.Serializable interface
    • Identify the fields that should be serializable
    • Have access to the no-arg constructor of its first nonserializable superclass

Institute of Computer Software

Nanjing University

the serializable interface1
The Serializable Interface
  • The class can optionally define the following methods:
    • writeObject (ObjectOutputStream)
    • readObject (ObjectInputStream)
    • writeReplace ()
    • readResolve ()

思考:如果一个可序列化的类实现了以上四个方法,那么在序列化和反序列化的过程中,这几个方法的调用次序如何?

Institute of Computer Software

Nanjing University

the externalizable interface
The Externalizable Interface

public interface Externalizable extends Serializable

{

public void writeExternal(ObjectOutput out) throws IOException;

public void readExternal(ObjectInput in) throws IOException, java.lang.ClassNotFoundException;

}

Institute of Computer Software

Nanjing University

the externalizable interface1
The Externalizable Interface
  • The class of an Externalizable object must do the following:
    • Implement the java.io.Externalizable interface
    • Implement a writeExternal method to save the state of the object
    • Implement a readExternal method to read the data written by the writeExternal method from the stream and restore the state of the object
    • Have the writeExternal and readExternal methods be solely responsible for the format, if an externally defined format is written
    • Have a public no-arg constructor

Institute of Computer Software

Nanjing University

the externalizable interface2
The Externalizable Interface
  • An Externalizable class can optionally define the following methods:
    • writeReplace
    • readResolve

Note: 声明类实现Externalizable接口会有重大的安全风险。writeExternal()与readExternal()方法声明为public,恶意类可以用这些方法读取和写入对象数据。如果对象包含敏感信息,则要格外小心。

Institute of Computer Software

Nanjing University

slide19
区别
  • Serializable
    • 自动存储必要信息,用以反序列化被存储的实例
    • 优点
      • 内建支持
      • 易于实现
    • 缺点
      • 占用空间过大
      • 速度慢
  • Externalizable
    • 只保存被存储的类的标识,完全由程序员完成读取和写入工作
    • 优点
      • 开销较少
      • 可能的速度提升
    • 缺点
      • 虚拟机不提供帮助,程序员负担重

Institute of Computer Software

Nanjing University

serialversionuid
serialVersionUID
  • privatestaticfinallongserialVersionUID
  • For compability
    • InvalidClassException
  • It is strongly recommended that all serializable classes explicitly declare serialVersionUID values
  • serialver;eclipse

Institute of Computer Software

Nanjing University

serialization principles
Serialization Principles
  • 如果该类有父类
    • 如果父类实现了可序列化接口,则OK
    • 如果父类没有实现可序列化接口,则父类所有字段的属性默认情况下不会被序列化
  • 如果该类的某个属性标识为static类型的,则该属性不能序列化;
  • 如果该类的某个属性采用transient关键字标识,则该属性不能序列化;

Institute of Computer Software

Nanjing University

serialization principles1
Serialization Principles
  • 在我们标注一个类可以序列化的时候,其以下属性应该设置为transient来避免序列化:
    • 线程相关的属性;
    • 需要访问IO、本地资源、网络资源等的属性;
    • 没有实现可序列化接口的属性;

Institute of Computer Software

Nanjing University

some items from effective java
Some Items from 《Effective Java》

Institute of Computer Software

Nanjing University

effective java for serialization
Effective Java for Serialization
  • 1. Implement Serializable judiciously 谨慎地实现Serializable
    • 代价1:一旦一个类被发布,则“改变这个类的实现”的灵活性将大大降低。
      • 序列化会使类的演化受到限制。
    • 代价2:增加了错误和安全漏洞的可能性。
      • 序列化机制是一种语言之外的对象创建机制。
    • 代价3:随着一个类的新版本的发行,相关的测试负担增加了。
      • 可序列化类的变化越大,它就越需要测试。

Institute of Computer Software

Nanjing University

effective java for serialization1
Effective Java for Serialization
  • Notes:
    • 为了继承而设计的类应该很少实现Serializable,接口也应该很少会扩展它。
    • 对于为继承而设计的不可序列化的类,应该考虑提供一个无参数的构造函数。
    • 内部类应该很少实现Serializable。

Institute of Computer Software

Nanjing University

effective java for serialization2
Effective Java for Serialization
  • 2. Consider using a custom serialized form 考虑使用自定义的序列化形式
    • 如果一个对象的物理表示等同于它的逻辑内容,则默认的序列化形式可能是合适的。
    • 即使确定了默认序列化形式是合适的,通常仍然要提供一个readObject方法以保证约束关系和安全性。

Institute of Computer Software

Nanjing University

effective java for serialization3
Effective Java for Serialization

Institute of Computer Software

Nanjing University

effective java for serialization4
Effective Java for Serialization

Institute of Computer Software

Nanjing University

effective java for serialization5
Effective Java for Serialization
  • 当一个对象的物理表示与它的逻辑数据内容有实质性的区别时,使用默认序列化形式有4个缺点:
    • 它使这个类的导出API永久地束缚在该类的内部表示上。
    • 它要消耗过多的空间。
    • 它要消耗过多的时间。
    • 它会引起栈溢出。

Institute of Computer Software

Nanjing University

effective java for serialization6
Effective Java for Serialization

Institute of Computer Software

Nanjing University

effective java for serialization7
Effective Java for Serialization
  • 如果所有的实例域都是transient的,那么省去调用defaultWriteObject和defaultReadObject也是允许的,但是不推荐这样做。
  • 在决定将一个域做成非transient之前,请一定要确信它的值将是该对象逻辑状态的一部分。
  • 不管你选择了哪种序列化形式,你都要为自己编写的每个序列化的类声明一个显式的序列化版本UID。

private static final long serialVersionID = randomLongValue

Institute of Computer Software

Nanjing University

effective java for serialization8
Effective Java for Serialization
  • 3. Write readObject methods defensively 保护性地编写readObject方法
    • readObject方法实际上相当于另一个共有的构造函数,如同其他构造函数一样,它也要求所有同样的注意事项:检查实参的有效性,并且必要时对参数进行保护性拷贝。

Institute of Computer Software

Nanjing University

versioning
Versioning
  • Versioning raises some fundamental questions about the identity of a class, including what constitutes a compatible change.
  • A compatible changeis a change that does not affect the contract between the class and its callers.

Institute of Computer Software

Nanjing University

incompatible changes
Incompatible changes
  • Deleting fields
  • Moving classes up or down the hierarchy
  • Changing a nonstatic field to static or a nontransient field to transient
  • Changing the declared type of a primitive field
  • Changing the writeObject or readObject method so that it no longer writes or reads the default field data or changing it so that it attempts to write it or read it when the previous version did not.

Institute of Computer Software

Nanjing University

incompatible changes1
Incompatible changes
  • Changing a class from Serializable to Externalizable or vice versa
  • Changing a class from a non-enum type to an enum type or vice versa
  • Removing either Serializable or Externalizable
  • Adding the writeReplace or readResolve method to a class is incompatible if the behavior would produce an object that is incompatible with any older version of the class.

Institute of Computer Software

Nanjing University

compatible changes
Compatible changes
  • Adding fields
  • Adding classes
  • Removing classes
  • Adding writeObject/readObject methods
  • Removing writeObject/readObject methods
  • Adding java.io.Serializable
  • Changing the access to a field
  • Changing a field from static to nonstatic or transient to nontransient

Institute of Computer Software

Nanjing University

slide38
摘要
  • 对象序列化
  • 对象持久化
    • Language level
    • Databases
  • Hibernate

Institute of Computer Software

Nanjing University

slide39
摘要
  • 对象序列化
  • 对象持久化
    • Language level
    • Databases
  • Hibernate

Institute of Computer Software

Nanjing University

object persistence
Object Persistence
  • During execution of application: objects are created and manipulated
  • What happens to objects after termination?
  • Various kinds of objects
    • Transient objects:
      • Disappear with current session
    • Persistent objects:
      • Stay around from session to session
      • May be shared with other applications (e.g. databases)

Institute of Computer Software

Nanjing University

approaches to manipulate persistent objects
Approaches to manipulate persistent objects
  • Persistence mechanisms from programming languages
  • Relational databases
  • Object-oriented databases

Institute of Computer Software

Nanjing University

persistence from programming languages
Persistence from programming languages
  • Mechanisms for storing objects in files and retrieving them
  • Simple objects:
    • e.g. integers, characters
    • conventional methods usable
  • Composite objects:
    • contain references to other objects
    • Persistence Closure principle:
      • Any storage and retrieval mechanism must handle the object and all its dependents.

 otherwise: dangling references

Institute of Computer Software

Nanjing University

slide43
对象结构的存储与提取
  • 对象持久化的难点之一:
    • 对象之间的引用

Institute of Computer Software

Nanjing University

slide44
对象结构的存储与提取
  • 需持久化整个对象引用闭包
    • Persistence closure
    • Java的serialization规则
      • 缺省规则:非static 非transient 的数据成员
      • 用户定义

class List implements Serializable {

List next;

private static final ObjectStreamField[] serialPersistentFields = {new ObjectStreamField("next", List.class)};

}

Institute of Computer Software

Nanjing University

slide45
对象结构的存储与提取
  • 闭包可能太大
    • 小对象引用(共享的)大对象

Institute of Computer Software

Nanjing University

slide46
对象结构的存储与提取
  • Java 的 transient 修饰子
    • Transient fields 不被序列化
    • Static fields 也不被序列化
    • 开发者负责维护

Institute of Computer Software

Nanjing University

schema evolution
Schema evolution
  • Fact: Classes change
  • Problem: Objects are stored of which class descriptions have changed
  • Schema evolution:
    • At least one class used by the retrieving system differs from its counterpart stored by the storing system.
  • Object retrieval mismatch (Object mismatch):
    • The retrieving system retrieves a particular object whose own generating class was different in the storing system.
  • No fully satisfactory solution

Institute of Computer Software

Nanjing University

different approaches
Different approaches
  • Naive, extreme approaches:
    • Forsake previously stored objects
    • Over a migration path from old format to new
      • a one-time, en masse conversion of old objects
      • not applicable to a large persistent store or to one that must be available continuously
  • Most general solution: On-the-fly conversion
  • Note: We cover only the retrieval part. Whether to write back the converted object is a separate issue.

Institute of Computer Software

Nanjing University

on the fly object conversion
On-the-fly object conversion
  • Three separate issues:
    • Detection:
      • Catch object mismatch
    • Notification:
      • Make retrieving system aware of object mismatch
    • Correction:
      • Bring mismatched object to a consistent state
      • Make it a correct instance of the new class version

Institute of Computer Software

Nanjing University

detection
Detection
  • Detect a mismatch between two versions of an object’s generating class
  • Two categories of detection policy:
    • Nominal approach:
      • Each class version has a version name
      • Central registration mechanism necessary
    • Structural approach:
      • Deduce class descriptor from actual class structure
      • Store class descriptor
      • Simple detection: compare class descriptors of retrieved object with new class descriptor

Institute of Computer Software

Nanjing University

detection structural approach
Detection: Structural Approach
  • What does the class descriptor need to contain?
  • Trade-off between efficiency and reliability
  • Two extreme approaches:
    • C1: class name
    • C2: entire class text (e.g. abstract syntax tree)
  • Reasonable approaches:
    • C3: class name, list of attributes (name and type)
    • C4: in addition to C3: class invariant

Institute of Computer Software

Nanjing University

notification
Notification
  • What happens when the detection mechanism has caught an object mismatch?
    • Language level mechanism
  • Class ANY could include a procedure:

correct_mismatchis

-- Handle object retrieval mismatch.

local

exception: EXCEPTIONS

do

createexception

exception.raise (‘‘[

Routine failure: Object mismatch during retrieval

]’’)

end

Institute of Computer Software

Nanjing University

correction
Correction
  • How do we correct an object that caused a mismatch?
  • Current situation:
    • Retrieval mechanism has created a new object (deduced from a stored object with same generating class)
    • A mismatch has been detected  new object is in temporary (maybe inconsistent) state

Institute of Computer Software

Nanjing University

correction1
Correction
  • 增加attribute
  • 删除attribute

Attribute was not in stored version.

Field is initialized to default value of attribute type

0.0

Attributes have not changed.

Stored version had a field.

New version has removed attribute.

Institute of Computer Software

Nanjing University

correction2
Correction

correct_mismatchis

-- Handle object retrieval mismatch

-- by correctly setting up balance.

do

balance := deposits.total - withdrawals.total

ensure

consistent: balance = deposits.total - withdrawals.total

end

900

100

200

deposits

old fields

withdrawals

240

300

new field

(initialized to default value)

Wrong!

balance 0.0

维护不变式

Institute of Computer Software

Nanjing University

slide56
自动对象转换:Java
  • serialVersionUID
    • 自动定义 (根据类文件生成)
      • 1. Class name 2. The class modifiers 3. The name of each interface 4. For each field of the class (except private static and private transient fields):
        • The name of the field
        • The modifiers of the field
        • The descriptor of the field
      • 5. For each method including constructors, except private methods and constructors:
        • The name of the method
        • The modifiers of the method
        • The descriptor of the method

Institute of Computer Software

Nanjing University

slide57
自动对象转换:Java
    • 手工指定
      • ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
      • 类改变时仍然能够反序列化
  • Java定义了一些“兼容”条件,符合条件的自动转换
    • 可以容忍的:adding fields, etc.
    • 太糟糕的: “Changing the type of a field”, deleting fields, etc

Institute of Computer Software

Nanjing University

slide58
对于实在“糟糕”的类修改
  • 可以定制序列化和反序列化方法

private void readObject(ObjectInputStream in) {}

private void writeObject(ObjectOutputStream out) {}

Institute of Computer Software

Nanjing University

slide59
摘要
  • 对象序列化
  • 对象持久化
    • Language level
    • Databases
  • Hibernate

Institute of Computer Software

Nanjing University

slide60
对象持久化与数据库
  • Deficiency of language level mechanisms
    • there is only one entry object;
    • there is no support for content-based queries;
    • each call to retrieved re-creates the entire structure, with no sharing of objects between successive calls;
    • there is no support for letting different client applications access the same persistent data simultaneously
  • a full-fledged solution requires taking advantage of database technology

Institute of Computer Software

Nanjing University

slide61
对象持久化与数据库
  • A set of mechanisms for storing and retrieving data items is a DBMS if it supports the following items:
    • Persistence
    • Programmable structure
    • Arbitrary size
    • Access control
    • Property-based querying
    • Integrity constraints
    • Administration
    • Sharing
    • Locking
    • Transactions

自然地,要用数据库

来存储持久化对象

Institute of Computer Software

Nanjing University

slide62
对象持久化与数据库
  • 关系型数据库:数据库的主流
    • A relational database is a set of relations, each containing a set of tuples (or records).
    • 关系代数
      • Selection, Projection , Join

Institute of Computer Software

Nanjing University

slide63

pages

“Stendahl”

“Balzac”

“Flaubert”

date

1830

1839

author

1833

“Stendahl”

341

307

425

346

1856

“The Carterhouse of Parma”

“The Red and the Black”

Title

“Eugėnie Grandet”

“Madame Bovary”

对象持久化与数据库
  • Operations: relational algebra: selection, projection, join
  • Queries: standardized language (SQL)
  • Usually “normalized”: every field is a simple value; it cannot be a reference

field name (= attribute)

Relation books:

tuple

(= row)

field

column

Institute of Computer Software

Nanjing University

operations

date

1839

1856

pages

307

425

author

“Stendahl”

“Flaubert”

“The Carterhouse of Parma”

Title

“Madame Bovary”

Operations
  • Selection: date > 1833
  • Projection
  • Join

Institute of Computer Software

Nanjing University

operations1

author

“Stendahl”

“Flaubert”

“Balzac”

Operations
  • Selection
  • Projection: on author
  • Join

Institute of Computer Software

Nanjing University

operations2

1783

“Honorė de Balzac”

“Henri Beyle”

1842

date

1830

1839

1856

“Gustave Flaubert”

pages

341

death

1833

346

author

“Stendahl”

“Stendahl”

“Flaubert”

“Balzac”

real name

“Henri Beyle”

307

1842

425

“Flaubert”

1880

1821

1850

1783

1821

1799

death

1842

1842

1799

1850

name

“Stendahl”

1880

“Stendahl”

1783

birth

birth

“Honorė de Balzac”

1783

“Henri Beyle”

“Henri Beyle”

real name

“Balzac”

“Gustave Flaubert”

“Eugėnie Grandet”

“Madame Bovary”

Title

“The Red and the Black”

“The Carterhouse of Parma”

Operations
  • Selection
  • Projection
  • Join: booksauthors

Relation authors:

Institute of Computer Software

Nanjing University

using relational databases with o o software

Relational

O-O

Using relational databases with O-O software
  • Comparison of terms:
  • Class library to provide operations (corresponding to embedded SQL).
    • e.g. JDBC

relation

tuple

field name

class

object

attribute

Institute of Computer Software

Nanjing University

object relational interoperability
object-relational interoperability
  • Appropriate usage cases:
    • You are writing an object-oriented system which must use and possibly update existing corporate data, stored in relational databases.
    • Your O-O software needs to store object structures simple enough to fit nicely in the relational view of things.
  • Otherwise, Impedance mismatch!

Institute of Computer Software

Nanjing University

impedance mismatch
Impedance Mismatch
  • 关系数据库
      • 数据结构规整,成员数目类型固定
      • 结构简单,成员类型属于一个既定小集合
      • 这些类型由大小固定的类型组合而成
  • 那么
    • 大小不定的域?
    • 表示对象引用的域?基于引用的间接查询?
    • 继承?
  • 更重要的是:对象identity语义

Institute of Computer Software

Nanjing University

object oriented databases
Object-oriented databases
  • Remove impedance mismatch
  • Overcome conceptual limitations of relational databases:
    • Data structure must be regular and simple
    • Small group of predefined types
    • Normal forms: no references to other “objects”
  • Attempt to offer more advanced database facilities

Institute of Computer Software

Nanjing University

requirements for oodbs
Requirements for OODBs
  • Minimal requirements:
    • Database functionality
    • Encapsulation: allow hiding the internal properties of objects and make them accessible through an official interface
    • Object identity: associate with each object an identification that is unique in the database
    • References: allow an object to contain references to other objects

Institute of Computer Software

Nanjing University

requirements for oodbs1
Requirements for OODBs
  • Additional requirements:
    • Inheritance
    • Typing
    • Dynamic binding
    • Object versioning
    • Schema evolution
    • Long transactions
    • Locking
    • Object-oriented queries

Institute of Computer Software

Nanjing University

oodbs examples
OODBs examples
  • Gemstone
  • Itasca
  • Matisse
  • Objectivity
  • ObjectStore
  • Ontos
  • O2
  • Poet
  • Matisse
  • Versant
  • at ETHZ: OMS Pro

Institute of Computer Software

Nanjing University

slide74
摘要
  • 对象序列化
  • 对象持久化
    • Language level
    • Databases
  • Hibernate

Institute of Computer Software

Nanjing University

slide75
为什么需要对象持久化框架?
  • OO中轻易实现的对象相同或相等,这样的关系在关系数据库中不存在。
  • OO的一项核心特性是继承,继承很重要,因为它允许创建问题的精确模型,同时可以在层次结构中自上而下的共享属性和行为。而关系数据库不支持继承的概念。
  • 对象之间可以轻易的实现一对一,一对多和多对多的关联关系,而关系数据库并不理解这些,它只知道外码指向主码。

Institute of Computer Software

Nanjing University

slide76
对象持久化框架
  • 对象关系映射(Object Relational Mapping,简称ORM)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。
    • ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。
  • O/R Mapper则指以O/R原理设计的持久化框架(Framework)
    • hibernate,ibatis,jdo,etc.

Institute of Computer Software

Nanjing University

slide77
应用分层
  • 当前的现实:
      • 两层结构
      • 三层结构
      • N-层结构

Institute of Computer Software

Nanjing University

no orm
No ORM
  • 使用 JDBC 操作数据库,业务处理逻辑和数据存取逻辑是混杂在一起的。一般基本都是如下几个步骤:1、建立数据库连接,获得 Connection 对象。2、根据用户的输入组装查询 SQL 语句。3、根据 SQL 语句建立 Statement 对象 或者 PreparedStatement 对象。4、用 Connection 对象执行 SQL语句,获得结果集 ResultSet 对象。5、然后一条一条读取结果集 ResultSet 对象中的数据。6、根据读取到的数据,按特定的业务逻辑进行计算。7、根据计算得到的结果再组装更新 SQL 语句。8、再使用 Connection 对象执行更新 SQL 语句,以更新数据库中的数据。9、最后依次关闭各个 Statement 对象和 Connection 对象。

Institute of Computer Software

Nanjing University

no orm1
No ORM
  • 优点:运行效率高
  • 缺点:嵌入大量SQL语句,项目难以维护
  • 主要原因:业务处理逻辑和数据存取逻辑完全混杂在一块

Institute of Computer Software

Nanjing University

hibernate
Hibernate
  • 它是连接Java应用程序和关系数据库的中间件
  • 它对JDBC API进行了封装,负责Java对象的持久化
  • 在分层的软件架构中它位于持久化层,封装了所有数据访问细节,使业务逻辑层可以专注于实现业务逻辑
    • 持久化层(Persistence Layer),即专注于实现数据持久化应用领域的某个特定系统的一个逻辑层面,将数据使用者和数据实体相关联
  • 它是一种ORM映射工具,能够建立面向对象的域模型和关系数据模型之间的映射

Institute of Computer Software

Nanjing University

slide84
对象-关系 映射
  • 简单映射
    • 将一个类中的一个数据成员定为关键字
    • 其它数据成员为属性

Institute of Computer Software

Nanjing University

slide85

Honey.java

Honey.hbm.xml

package de.laliluna.example;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.GeneratedValue;

@Entity

public class Honey {

@Id

@GeneratedValue

private Integer id;

private String name;

private String taste;

public Honey() {}

public Integer getId() { return id;}

public void setId(Integer id) { this.id = id; }

public String getName() { return name;}

public void setName(String name) {this.name = name;}

public String getTaste() {return taste;}

public void setTaste(String taste) {this.taste = taste;}

@Override

public String toString() {

return "Honey: "+getId()+" Name: "+getName()+" Taste: "+getTaste();

}

}

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="de.laliluna.example">

<class name="Honey" table="thoney">

<id name="id">

<generator class="increment"/>

</id>

<property name="name" column="fooname"/>

<property name="taste" column="bartaste"/>

</class>

</hibernate-mapping>

Institute of Computer Software

Nanjing University

slide86
对象-关系 映射
  • 继承:
    • 方案1:继承关系中每个具体类对应一个表
      • 子类父类各自映射到各自的关系上
      • 特点:在这种映射方式中,每个子类除了映射自己的属性外,还需要映射从父类继承来下的属性;此方式中关系数据模型完全不支持对象的继承关系,不支持多态关联和多态查询

Institute of Computer Software

Nanjing University

slide87
对象-关系 映射
  • 继承
    • 方案 2:基类(根类)对应一个表
      • 所有继承自一个类的类都映射到一个表上
      • 增加一栏标记当前记录对应的对象的类
      • 特点:这种映射方式支持多态关联和多态查询,并且能获得最佳查询性能,缺点是需要对关系数据模型进行非常规设计,在数据库表中加入额外的区分各个子类的字段,此外,不能为所有子类的属性对应的字段定义not null约束,无法保证关系数据模型的数据完整性

Institute of Computer Software

Nanjing University

slide88
对象-关系 映射
  • 继承
    • 方案 3:每个类对应一个表
      • 父类映射的关系与子映射的关系共享相同的主键值,父类关系只记录本身的属性,如果要查询的是子类,则透过外键参考从父类表格中取得继承而來的属性值。
      • 特点:这种映射方式支持多态关联和多态查询,而且符合关系数据模型的常规设计规则,缺点是它的查询性能不如第二种映射方式。在这种映射方式下,必须通过表的内连接或左外连接来实现多态查询和多态关联。

Institute of Computer Software

Nanjing University

slide91
对象-关系 映射 (继承)

1、复杂度:

[方案1]包含重复字段;

[方案2]简单;

[方案3]表较多且之间有外键约束;

2、查询性能:

[方案1]若查询父类需查所有子类表;

[方案2]效率高;

[方案3]需要表内连接或左外连接;

3、可维护性:

[方案1]若父类属性变化需要修改所有子类对应的表;

[方案2]只需修改一个表;

[方案3]若某个类属性变化只修改这个类对应的表;

综上,选择时,可以参考以下原则:

1、子类属性不是非常多时,优先考虑[方案2],因为其性能最佳。

2、子类属性非常多,且对性能要求不是很严格时,优先考虑[方案3]。

slide92
对象-关系 映射
  • Set 映射
    • 对象中某属性是一个集合
      • 集合元素仅仅是值,无identity
    • 映射到另一个关系,用外键表明其属于哪个对象
  • List 映射
    • 与Set类似 再加一栏表示位置

Institute of Computer Software

Nanjing University

slide93
对象-关系 映射
  • Map映射
    • Key-Val 属于谁
  • Set 和 Map可排序

Institute of Computer Software

Nanjing University

slide94
对象-关系 映射
  • 映射实体关联关系
    • 一对一
    • 一对多
    • 多对一
    • 多对多

Institute of Computer Software

Nanjing University

slide95
作业
  • Java语言“transient”关键字与对象序列化有何关系?
  • Java语言中实现Serializable接口和Externalizable接口有何不同?
  • 对象序列化与反序列化时的“Schema evolution”问题具体指什么?一般如何处理之?
  • 为何对象持久化要使用数据库?对象模型和关系模型之间有哪些不匹配?何谓对象关系映射?
  • 尝试学习、使用Hibernate。(此题不需提交)

Institute of Computer Software

Nanjing University