Transcript UML Models

Data Source Architectural
Patterns – Hiding SQL
Ralph Johnson
1
SQL
Another language
Standard – sort of
Not object-oriented
Can have duplication
Can be slow
CS327
16-2
SQL
Tables
Rows
Queries
Select
Project
Sum
Update
…
CS327
16-3
SQL
Database connection
Socket to a DBMS
Send SQL and get rows
String sql = “SELECT * FROM person WHERE id = ?”;
IDbCommand comm = new OleDbCommand(sql, DB.Connection);
Comm.Parameters.Add(new OleDbParameter(“key”,key));
IDataReader reader = comm.Execute();
CS327
16-4
How to implement domain
model
Transaction script –
Table Data Gateway
Row Data Gateway
Domain model –
Active Record
Data Mapper
Table module –
Table Data Gateway
CS327
16-5
Table Data Gateway
Put all SQL about a table in the same
class, the Table Data Gateway.
One instance of that class.
Instance variable: database connection
Operations:
findAll, findPerson, findWithAge, …
insert, delete, …
CS327
16-6
Row Data Gateway
Put all SQL about a table in the same
class, the Row Data Gateway.
One instance for each row.
Methods contain only SQL
Instance variables just row fields
“Find” operations
Static methods
In a builder object
CS327
16-7
Active Record
Like Row Data Gateway except
Some methods are domain logic
Some variables not stored in database
Designed more for domain model than for
database
CS327
16-8
Data Mapper
Moves data between domain objects and
database
Domain objects know little about data
mapper
Database design independent of domain
model
Might look more like Table Data Gateway
CS327
16-9
Data Mapper
Persistent object knows data mapper
Has operation like “store”
Persistent object does not know d.m.
personMapper.store(aPerson)
One mapper for each class, or one for
entire application
CS327
16-10
Transaction script
Embedded SQL
Move SQL into class for the table
Table Data Gateway
Make an instance for each row
Data Row Gateway
Move behavior into row, encapsulating data
Active Record
CS327
16-11
Why Table Data Gateway?
Separate SQL from logic
Can change DBMS easier
Oracle to DB2 or Access
SQL to XML
CS327
16-12
Why Row Data Gateway?
Reduce duplication
Make it easier to add/remove fields
CS327
16-13
Why Active Record?
Reduce duplication
Transaction scripts can become very
simple, just descriptions of use case
CS327
16-14
Why Data Mapper
Separate SQL from domain logic
Make it easier to change database
CS327
16-15
Conclusion
Think of these patterns are refactorings
Start simple, become complex as needed
CS327
16-16