• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

You need to save a Java object permanently. Should you serialize it to a byte stream, or map it to a relational database? What are the trade-offs?

Core Idea

AspectSerializationORM (Object-Relational Mapping)
Storage formatByte blob (unreadable)Relational table (readable)
QueryingCannot query (must deserialize everything)Full SQL queries (SELECT * WHERE balance > 1000)
DebuggingHard (blob is unreadable)Easy (inspect table with SQL)
ToolingBuilt into Java (Serializable)Requires ORM tool (Hibernate, TopLink, JDBC)
PerformanceFast for single objectsBetter for large datasets (indexed queries)
EJB Entity BeansNot usedUsed (JDBC for BMP, container for CMP)

How It Works

Serialization approach:

// Save
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("account.dat"));
oos.writeObject(bankAccount);
// Load
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("account.dat"));
BankAccount account = (BankAccount) ois.readObject();

ORM approach:

// Save (BMP style with JDBC)
PreparedStatement ps = conn.prepareStatement("INSERT INTO accounts (id, owner, balance) VALUES (?, ?, ?)");
ps.setString(1, account.getAccountID());
ps.setString(2, account.getOwnerName());
ps.setDouble(3, account.getBalance());
ps.executeUpdate();

Visual Explanation

SerVsORM cluster_ser Serialization cluster_orm ORM Obj BankAccount Object SerFile account.dat [byte][byte][byte]... Obj->SerFile Table accounts table | ID | Owner | Balance | | 1 | Ray | 1000 | | 2 | Bob | 1500 | Obj->Table SerQ Query: 'Find balance > 1000' Answer: Must deserialize ALL objects! ORMQ Query: SELECT * FROM accounts WHERE balance > 1000 Answer: Bob (1500)!

Key Properties

  • ORM is superior for business data: Queryability and debuggability win for enterprise apps
  • Serialization still useful: For caching, session replication in clusters, simple use cases
  • Entity beans mandate ORM: The EJB spec envisions ORM (not serialization) for entity beans
  • Modern ORM tools: Hibernate (most popular), TopLink, JDO—reduce manual JDBC code

Connections

Edge Cases & Gotchas

  • Serialization version UID: If you change the class, deserialization fails without serialVersionUID
  • ORM impedance mismatch: Object model ≠ relational model (inheritance, collections are hard to map)
  • EJB 3.x uses JPA: Java Persistence API—modern evolution of EJB entity beans + ORM