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
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., twoEmployeeobjects 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 : InheritanceWhy 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
Transactiontable withamount,status, and aupdateStatus()trigger. - OODBMS approach: A
Transactionobject wherestatusis private, and onlyprocess()orrollback()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 overriddenarea()methods).
Worked Example: Daraz’s Inventory System Daraz stores products as objects with inheritance:
- Superclass:
Product(attributes:id,price,stock). - Subclasses:
Electronics(inheritsprice+ addswarrantyPeriod),Clothing(addssize,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
Ordercontains anOrderItemobject (which itself hasProductandquantity). - Collections: A
Coursehas aList<Student>(not a separateEnrollmenttable). - References: A
Professorreferences aDepartment(foreign key equivalent).
Real-world tie-in: NEPSE’s stock portfolio
- A
Portfolioobject contains aList<Holding>(eachHoldingis an object withStock,quantity, andpurchaseDate). - 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.
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:
- NEPSE: Uses OODBMS for stock entities (inheritance for
Stock→Equity/Debenture) and nested objects forTradehistory. - eSewa: Hybrid system—relational for user accounts but OODBMS for transaction workflows (e.g.,
Paymentobjects withprocess()methods). - Pathao: OODBMS for dynamic route calculations (objects represent
Location,Vehicle,Driverwith methods likecalculateEta()).
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(methodprocess()). - Subclasses:
VoicePacket,DataPacket(each overridesprocess()for QoS handling).
2. Aggregation vs. Composition
- Aggregation: "Has-a" relationship (e.g.,
DepartmenthasProfessorobjects;Professorcan exist withoutDepartment). - Composition: Strong ownership (e.g.,
CarcontainsEngine;Enginecannot exist withoutCar).
Example: Bank Loan System
LoancomposesRepaymentSchedule(schedule is meaningless without the loan).LoanaggregatesCustomer(customer exists independently).
Exam Tip: How to Score Full Marks
- Diagrams are mandatory: Draw class hierarchies (e.g.,
Vehicle→Car/Bike) and object structures (e.g.,Order→OrderItem→Product) for schema questions. - 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'
- SQL:
- 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
Productsuperclass with common attributes (id,price). Subclasses likeElectronicsaddwarrantyPeriod, avoiding redundant columns in relational tables." - Short-answer traps:
- Encapsulation: "Why can’t you directly update an
Employee.salaryin OODBMS?" Answer: "Attributes are private; access is controlled via methods likesetSalary()to enforce business rules (e.g., salary caps)." - OID: "How does an OODBMS distinguish two
Employeeobjects with the same name?" Answer: "Each object has a uniqueOID(Object Identifier), independent of attribute values."
- Encapsulation: "Why can’t you directly update an
- Problem-solving steps:
For queries, always:
- Identify the root object (e.g.,
Order). - Trace paths (e.g.,
Order.items.product.name). - Add filters (e.g.,
WHERE items.quantity > 0).
- Identify the root object (e.g.,
Final Visual Summary:
Based on the TU BSc CSIT syllabus for Distributed and Object Oriented Database, unit 5.
Discussion
Loading…