Elective Distributed and Object Oriented Database

Distributed and Object Oriented DatabaseUnit 510 min read

Object Oriented Database: Models, Inheritance & Querying

Unit 5 of Distributed and Object Oriented Database covers OODBMS fundamentals—object models, inheritance hierarchies, encapsulation, and query languages (OQL)—with comparisons to relational databases, real-world applications in Nepal (e.g., NEPSE stock tracking), and exam-focused problem-solving techniques.

TAKEAWAYS:

  • OODBMS stores data as objects (with attributes, methods, and identity) instead of tables, enabling complex relationships and behaviors like inheritance.
  • Encapsulation hides internal state while exposing methods (e.g., BankAccount.withdraw()), unlike relational DBs where data is exposed directly.
  • Inheritance lets subclasses reuse parent class properties (e.g., Vehicle → Car/Bike), reducing redundancy in schemas like NEPSE’s stock entity hierarchy.
  • OQL (Object Query Language) extends SQL with path expressions (e.g., SELECT p.employees FROM Project p) to traverse object graphs.
  • OODBMS excels in spatial/temporal data (e.g., Pathao’s dynamic route calculations) but lacks ACID guarantees for transactions compared to RDBMS.
  • Hybrid systems (e.g., PostgreSQL with JSONB) blend relational and object models for flexibility in modern apps like eSewa’s transaction logs.

Core Concepts: Objects vs. Relations

OODBMSMethodsObjects with OIDRDBMSStored ProceduresTables with PK
Key differences: OODBMS models data as objects with behavior, while RDBMS uses tables with stored procedures.

1. The Object Model: Beyond Tables

Relational databases store data in flat tables (rows = tuples, columns = attributes), but OODBMS models data as objects with:

  • Identity: Each object has a unique OID (Object Identifier), even if attributes are identical (e.g., two Employee objects with the same name but different IDs).
  • State: Attributes define the object’s data (e.g., Employee.name, salary).
  • Behavior: Methods (functions) define operations (e.g., calculateBonus()).
classDiagram
    class Employee {
        -String name
        -double salary
        +calculateBonus()
    }
    class Manager {
        -List~Employee~ team
        +assignProject()
    }
    Employee <|-- Manager : Inheritance

Why this matters: In NEPSE’s stock trading system, a Trade object isn’t just a row—it has methods like execute() or cancel(), and its Order sub-objects inherit properties like priority.


2. Encapsulation: Data Hiding with Methods

In OODBMS, attributes are private by default, and access is controlled via methods. Compare this to SQL, where you directly UPDATE salary = 50000 in an Employee table.

Feature Relational DB (SQL) OODBMS
Data Access Direct (UPDATE, SELECT) Via methods (setSalary())
Example UPDATE accounts SET balance = balance - 1000 account.withdraw(1000)
Security Model Row-level permissions Method-level encapsulation

Real-world example: Khalti’s transaction system

  • Relational approach: A Transaction table with amount, status, and a updateStatus() trigger.
  • OODBMS approach: A Transaction object where status is private, and only process() or rollback() methods can change it. This prevents invalid states (e.g., a transaction marked as "completed" without processing).

3. Inheritance: Hierarchies in Schemas

OODBMS supports class hierarchies, where subclasses inherit attributes/methods from superclasses. This mirrors real-world relationships, like:

  • Vehicle (superclass) → Car, Bike (subclasses).
  • Shape → Circle, Rectangle (with overridden area() methods).
seats: inthonker(): voidCarhasSidecar: booleanbalance(): voidBikeVehicle
Abstract Vehicle superclass with concrete subclasses (Car and Bike) showing inherited/overridden members.

Worked Example: Daraz’s Inventory System Daraz stores products as objects with inheritance:

  • Superclass: Product (attributes: id, price, stock).
  • Subclasses: Electronics (inherits price + adds warrantyPeriod), Clothing (adds size, material).
  • Query: "Find all Electronics with warranty > 2 years" uses OQL’s path expressions:
    SELECT p FROM Electronics p WHERE p.warrantyPeriod > 2
    

4. Complex Object Structures

OODBMS supports nested objects, collections, and references without joins:

  • Nested Objects: An Order contains an OrderItem object (which itself has Product and quantity).
  • Collections: A Course has a List<Student> (not a separate Enrollment table).
  • References: A Professor references a Department (foreign key equivalent).
Productquantity: intOrderItemOrder
Nested object structure: Order → OrderItem → Product (no joins needed).

Real-world tie-in: NEPSE’s stock portfolio

  • A Portfolio object contains a List<Holding> (each Holding is an object with Stock, quantity, and purchaseDate).
  • No need for joins: portfolio.getTotalValue() traverses the nested structure automatically.

Querying Objects: OQL Basics

OQL (Object Query Language) extends SQL with path expressions and method invocations.

SELECT e.name FROM Employee eWHERE e.salary > 50000ORDER BY e.nameTOP
OQL query structure: SELECT → FROM → WHERE → ORDER BY (no JOINs needed for nested objects).

Key OQL Features

Feature SQL Example OQL Example
Path Expressions SELECT e.department FROM Employee e SELECT e.department.name FROM Employee e
Method Invocation N/A SELECT p FROM Product p WHERE p.getDiscount() > 0.1
Collection Queries SELECT * FROM Employee WHERE salary IN (SELECT max_salary FROM Departments) SELECT e FROM Department d, e IN d.employees WHERE e.salary > d.avgSalary()

Worked Example: Pathao’s Driver Earnings Query: "Find all drivers in Kathmandu who drove >100 trips and earn >Rs. 20,000/month."

SELECT d FROM Driver d
WHERE d.location.city = "Kathmandu"
  AND d.trips.size() > 100
  AND d.calculateMonthlyEarnings() > 20000

OODBMS vs. Relational DBs: When to Use Which

Criteria OODBMS Relational DB (RDBMS)
Data Model Objects with methods Tables with rows/columns
Relationships References, inheritance Foreign keys, joins
Query Language OQL (path expressions) SQL (joins, subqueries)
Best For Complex hierarchies (e.g., CAD, multimedia) Structured data (e.g., banking transactions)
Transactions ACID per object group ACID per table/row
Scalability Horizontal (sharding by object) Vertical (partitioning)

Nepal-Specific Use Cases:

  1. NEPSE: Uses OODBMS for stock entities (inheritance for Stock → Equity/Debenture) and nested objects for Trade history.
  2. eSewa: Hybrid system—relational for user accounts but OODBMS for transaction workflows (e.g., Payment objects with process() methods).
  3. Pathao: OODBMS for dynamic route calculations (objects represent Location, Vehicle, Driver with methods like calculateEta()).

Advanced: Object-Oriented Features in Depth

1. Polymorphism: Overriding Methods

Subclasses can override superclass methods. Example:

class Shape {
    double area() { return 0; }
}
class Circle extends Shape {
    double area() { return Math.PI * radius * radius; }
}

OQL Example:

SELECT s.area() FROM Shape s WHERE s.name = "Circle"

Real-world: NTC’s network traffic analysis

  • Superclass: Packet (method process()).
  • Subclasses: VoicePacket, DataPacket (each overrides process() for QoS handling).

2. Aggregation vs. Composition

  • Aggregation: "Has-a" relationship (e.g., Department has Professor objects; Professor can exist without Department).
  • Composition: Strong ownership (e.g., Car contains Engine; Engine cannot exist without Car).
aggregation (weak)composition (strong)DepartmentProfessorCarEngine
Aggregation (Department-Professor) vs. Composition (Car-Engine) relationships.

Example: Bank Loan System

  • Loan composes RepaymentSchedule (schedule is meaningless without the loan).
  • Loan aggregates Customer (customer exists independently).

Exam Tip: How to Score Full Marks

  1. Diagrams are mandatory: Draw class hierarchies (e.g., Vehicle → Car/Bike) and object structures (e.g., Order → OrderItem → Product) for schema questions.
  2. OQL vs. SQL: Always show both for comparison. For example:
    • SQL: SELECT e.name FROM Employee e JOIN Department d ON e.dept_id = d.id WHERE d.location = 'Kathmandu'
    • OQL: SELECT e.name FROM Employee e WHERE e.department.location = 'Kathmandu'
  3. Real-world mapping: Relate inheritance to NEPSE’s stock types or Pathao’s vehicle classes. Example:

    "Explain how OODBMS inheritance reduces redundancy in Daraz’s product catalog." Answer: "Daraz uses inheritance to define a Product superclass with common attributes (id, price). Subclasses like Electronics add warrantyPeriod, avoiding redundant columns in relational tables."

  4. Short-answer traps:
    • Encapsulation: "Why can’t you directly update an Employee.salary in OODBMS?" Answer: "Attributes are private; access is controlled via methods like setSalary() to enforce business rules (e.g., salary caps)."
    • OID: "How does an OODBMS distinguish two Employee objects with the same name?" Answer: "Each object has a unique OID (Object Identifier), independent of attribute values."
  5. Problem-solving steps: For queries, always:
    1. Identify the root object (e.g., Order).
    2. Trace paths (e.g., Order.items.product.name).
    3. Add filters (e.g., WHERE items.quantity > 0).

Final Visual Summary:

Based on the TU BSc CSIT syllabus for Distributed and Object Oriented Database, unit 5.

Discussion

Loading…