Object Oriented Persistence Middleware System Architectures Principles and
Object Oriented Persistence Middleware System Architectures Principles and techniques Persistence Managers: OJB, Hibernate 1
References 4 S. Ambler: The Design of a Robust Persistence Layer http: //www. ambysoft/persistence. Layer. pdf 4 S. Ambler: Encapsulating Database Access http: //www. agiledata. org/essays/implementation. Strategies. html 4 Java Data Objects http: //access 1. sun. com/jdo/ 4 The Object Relational Bridge (OJB) http: //db. apache. org/ojb/index. html 4 Relational Persistence For Idiomatic Java http: //www. hibernate. org/ 4 Gopalan Suresh Raj: Java Data Objects (JDO) http: //my. execpc. com/~gopalan/java/jdo. html 4 Joseph W. Yoder, Ralph E. Johnson, et al. : Connecting Business Objects to Relational Databases. In Proceedings of the 5 th Conference on the Pattern Languages of Programs, Monticello-IL-EUA, August 1998. http: //citeseer. nj. nec. com/yoder 98 connecting. html 2
Architecture for Persistent objects 4 Design principles 4 Keep language clean from DB access code 4 "persistence manager" between client code and DB 4 DB specific code generated for use by the persistent mgr Persistence Manager API for Application Program ? ("Business Logic" ) ODMG OQL EJB-QL Java Data Objects JDO Ad hoc Mapping to Database? Object/ Relational mapping, e. g. - OJB ("Object Rel. Bridge") - many vendor products 3
Persistence Layer 4 Benefits 4 Reduction of database and object schema coupling 4 Implementation of DB related code in one place: less effort for adapting to DB schema changes ("evolution") 4 Makes application development easier: concentrate on application logic but DB access code 4 Allows for data oriented business rules e. g. "if an employee earns more than 100 K he/she does not get overtime payment" But integrity constraints? 4 Risks 4 Direct DB access is easier for small applications -> investment required 4 Loose of control over DB access, e. g. when to write objects to DB example: EJB Container Managed Persistence 4 Replication of DB functionality 4 Programming language dependent 4
Principle Persistence Architectures 4 Traditional: Direct database access Business objects 4 Separate Data Access objects 4 Persistence Layer 4 Transaction facilities 4 Query language mapping 4 … and much more 4 Services Data Access objects 5
Direct DB acces Customer Construct select Work on data select Result set 4 Violates most of the design principles 4 No "separation of concerns" 4 … which means here: application logic and DB access should be separated n Schema evolution n DB-vendor independence (but language independence is missing from most frameworks) 6
Direct data access Customer find(int cid); Customer[] find(String name); Customer[] find(String phone); …. • SQL / OQL/. . statements for implementing the "customer" operations • JDBC standard when using Java • … but code is written quickly • viable for small applications 7
Data Access Objects (DAO) Customer Data. Source Customer Data read(customer) get. Key. Val() keyvalues Construct select Set data values Result set 4 Encapsulation of DB access logic in classes independent from business objects 4 Typically one access object for each business object 4 Access Objects may or may not follow standards (Active. X ADO, JDO), 8
Persistence Framework 4 Mapping between DB data and objects defined in a Meta Data Repository (XML document, database, …) 4 Basic functionality: create, read, update, write, transaction support 4 Enhanced: fault tolerance, mapping generation, caching etc. Figure © S. Amber 9
Persistence Framework 4 Features 4 Implicit persistence: - framework automatically makes business objects persistent - no action taken by application program n Examples: Enterprise Java Beans, Java Data Objects (container managed) 4 Explicit persistence - application program indicates when to save n Most common in Persistence frameworks 4 DB access generated. . n dynamically: flexible n at compile time: simpler, better performance n during system start up (example: Hibernate framework) 10
Persistence Framework 4 Reading a business object via persistence framework Persistence Framework Customer Mapping class read(customer) get. Data. Values() keyvalues get. Map Construct select Set data values select Result set 11
Persistence Framework 4 Steps during Data access in Meta Data driven Architecture Figure © S. Amber 12
Meta Data driven persistence architecture 4 Example(1) Meta data Query for "Return all orders placed Jan. 27, 2003" <Query> <Search For>Order</Search For> <Clause> <Attribute> “date. Ordered” </Attribute> <Comparison> “=” </Comparison> <Value> “ 27 -Jan-2003” </Value> </Clause> <Attribute> “subtotal. Before. Tax” </Attribute> <Comparison> “>=” </Comparison> <Value> “ 1000. 00” </Value> </Clause> </Query> 13
Meta Data driven persistence architecture Example(2): Mapping for Order class / table Property Column Order. order. ID Order. date. Ordered Order. Date. Ordered Order. date. Fulfilled Order. Date. Fulfilled Order. get. Total. Tax() Order. Tax Order. subtotal. Before Tax Order. Subtotal. Before. T ax Order. ship. To. person. I D Order. Ship. To. Contact. ID Order. bill. To. person. ID Order. Bill. To. Contact. ID Order. last. Update Order. Last. Update Mapping typically very simple 14
Meta Data driven persistence architecture 4 Example (3) SELECT * FROM Order WHERE Order. Date. Ordered = ‘ 2003 -01 -27’ AND Order. Subtotal. Before. Tax >= 1000. 00 4 Result presentation generated as well 4 More sophisticated mappings needed … but not provided in most frameworks 4 How to employ efficient data base query processing when loading objects? 15
Persistence framework 4 Why complex mappings are needed Customer Order Item Customer item Order Customer object with two orders and two / one items Data base representation using three tables Wanted: All Customers located in Berlin with orders of july 30 with items not yet delivered (Items may be delivered individually) 16
Persistence framework 4 Complex mapping (cont. ) Select c. name, c. something, o. id, o. etc, i. no, i. etc from customer c, order o, item i where o. cid = c. cid and c. city="Berlin" and o. date="7 -30 -2003" and i. id in (select j. id from item j where j. oid = o. oid and j. delivered = false) 4 Map result tuples to objects customer, order, item 4 Inefficient alternative: 4 Access tables independently Many independent data base accesses: customer, for each customer his order, for each order its items: expensive 4 Implementation issue: Lazy loading, otherwise the object construction will take some time…. 17
Services 4 Service: an operation offered by a computing entity that can be invoked by other computing entities (Ambler) 4 Examples 4 Corba 4 Web services 4 Stored procedures 18
Services Goal: Encapsulate access to legacy data get. Data. Values() Read Customer Service Customer read(id) Wrapper class read. Customer(id) Construct select Key values select Customer data XML Result set XML Build Set data values 19
Comparison: DB access from business object Advantage Disadvantage When to use Very simple approach. Directly couples your At beginning of a object schema to your project when your Can develop code data schema. persistence approach very quickly. is still in flux. Application developers Can support access need to learn For small applications to very bad database access (less than 20 business designs (although language (e. g. SQL) classes) and/or performance may Database refactoring prototypes. suffer). impeded due to high coupling. Difficult to reuse database access code. © S. Amber 20
Comparison: DB access via Data objects Advantage Disadvantage When to use Database access code encapsulated into its own set of classes. Object schema still coupled to your data schema, via the data access objects. Medium-sized application (20 -100 business classes). . Business classes no longer coupled to database. Database refactoring easier due to lowered coupling. Application developers need to learn SQL. Often platform specific. . Can support access to very bad data designs (although performance may suffer). Possible to reuse data access objects. ). 21
Comparison: DB access via persistence framework Advantage Disadvantage When to use Application programmers do not need to know the data schema. Perceived performance impact to your applications (if the framework is poorly built). Medium and large sized applications. Application programmers don’t even need to know where the data is stored. Frameworks reflect performance expertise of its builders Administration facility can ease database refactoring because it simplifies impact analysis by tracing columns to object attributes. Administration facility aids performance tuning because it makes it easy to change mappings. Requires reasonably clean data designs because the framework may not support the overly complex mappings. Often platform specific. Possible to reuse framework and mapping meta data between applications. 22 When it is common practice within your organization to use a persistence framework.
Comparison: Service access to data Advantage Disadvantage When to use Potential to create platform independent services. Web services standards and tools still evolving. Medium to large sized applications. Performance becomes a problem when combining several services in serial or simply when services are invoked across a network. . Whenever an appropriate service already exists that you can reuse. Web services quickly becoming an industry standard. Supports reuse between applications. © S. Amber 23
Persistence Frameworks 4 Ob. Ject. Relational. Bridge (OJB) 4 O/R Mapping tool and persistance framework by Apache (open source) 4 Supports various interfaces to application objects n ODMG 3. 0 n JDO n Custom. Language OJB 4 Sophisticated mappings (1: n, n: n) 4 Cache 4 Lazy loading 4 Distributed lock management (pessimistic) 4 In addition optimistic synchronisation 4 Prefetching relations 4 Interface to many relational DBS 24
Persistence Frameworks: Hibernate 4 Hibernate (free software , LGPL) 4 mapping at startup time 4 High performance 4 Mapping using reflection facilities 4 Custom language 4 ODMG 3. 0 as beta implementation 4 Lazy loading 4 Cache and query cache (optional) 4 Outer join, loading object graph with one select 4 Optimistic synchronisation 4 Extensive documentation 25
Hibernate example 4 The database CREATE TABLE `users` ( `Logon. ID` varchar(20) NOT NULL default '0', `Name` varchar(40) default NULL, `Password` varchar(20) default NULL, `Email. Address` varchar(40) default NULL, `Last. Logon` datetime default NULL, PRIMARY KEY (`Logon. ID`) ); From tutorial by Glen Smith 26
Hibernate example 4 The application classes public class User { private String user. ID; private String user. Name; private String password; private String email. Address; private Date last. Logon; public String get. ID() { return user. ID; } public void set. ID(String new. User. ID) { user. ID = new. User. ID; } //. . . a bunch of other properties // using get. XXX() and set. XXX() go in here. . . } 27
Hibernate example 4 Defining the mapping <? xml version="1. 0"? > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate Mapping DTD//EN" "http: //hibernate. sourceforge. net/hibernate-mapping. dtd"> <hibernate-mapping> <class name="dbdemo. User" table="users"> <id name="ID" column="Logon. Id" type="string"> <generator class="assigned"/> </id> <property name="user. Name" column="Name" type="string"/> <property name="password" type="string"/> <property name="email. Address" type="string"/> <property name="last. Logon" type="date"/> </class> </hibernate-mapping> 28
Hibernate example 4 Define Database (property file) 4 Create Datastore object Datastore ds = Hibernate. create. Datastore(); ds. store. File("My. Mapping. File. hbm. xml") 4 Build session object session 4 Business logic, custom query language List my. Users = session. find("from user in class dbdemo. User where user. ID = ? ", "joe_cool", Hibernate. STRING); if (my. Users. size() > 0) { for (Iterator i = my. Users. iterator(); i. has. Next() ; ) { User next. User = (User) i. next(); System. out. println("Resetting password for User: " + next. User. get. User. Name()); next. User. set. Password("secret"); } } else { System. out. println("Didn't find any matching users. . "); } 4 Close session 29
Persistence Manager for Java Data Objects 4 Basic architecture for JDO persistence manager Source code enhancement (c) Gopalan Suresh Raj (http: //gsraj. tripod. com/) 30
- Slides: 30