SlideShare a Scribd company logo
Professional Open Source™




           Persistence and Domain Modelling




© JBoss, Inc. 2003, 2004.                                07/17/04   1
The persistence layer
                                                                       Professional Open Source™


  How does the Java application interact with the SQL database?
  Application layers
           – group related code by concern
           – prevent leakage of concerns
           – have clear interfaces to avoid inter-layer dependencies


  A typical Layered Architecture and its interface dependencies:
                                 Presentation Layer

                                                            Utility
                                                             and
                                  Business Layer
                                                           Helper
                                                           Classes

                                 Persistence Layer




© JBoss, Inc. 2003, 2004.                                                                          2
What is persistence?
                                                                        Professional Open Source™


  “Persistence”
           – where data (state) outlives the process that created it


  In object-oriented applications:
           – objects in a system are by default transient
           – some of the objects in the graph are made persistent
           – this subgraph of persistent instances can later be re-created in the same
             process or another process


  We need a data model and data store for persistent data...

                                  The Relational Data Model and
                             SQL-based Database Management Systems.




© JBoss, Inc. 2003, 2004.                                                                           3
PERSISTENCE APPROACHES
                                                        Professional Open Source™




  1. A well-know and widely used DAO design pattern to wide complex
  JDBC code and no portable SQL from business logic.




                           ORM also uses DAO pattern




© JBoss, Inc. 2003, 2004.                                                           4
PERSISTENCE APPROACHES
                                                                   Professional Open Source™




  2. EJB entity beans (CMP)
     Not fully object-oriented
 
     Doesn’t support polymorphic associations and queries
 
  Not portable across application servers

                Persistence runs only with EJB container


                           In EJB3 no CMP, uses ORM for persistence
                           Hibernate is good for JBOSS and major app. Servers
                           Top Link is good for Oracle app. server



© JBoss, Inc. 2003, 2004.                                                                      5
PERSISTENCE APPROACHES
                                                           Professional Open Source™




  3. Object-oriented database system (ODBMS)
                 JDO (Java Data Objects) are popular.
                 But, object-databases are not widely adopted.




© JBoss, Inc. 2003, 2004.                                                              6
PERSISTENCE APPROACH
                                                           Professional Open Source™




 4. THE BEST FOR THE MOST PROBLEMS
  ORM (Object-Relation Model)

  An API for performing basic CRUD operations on objects of persistent
   classes
  A language or API for specifying queries that refer to classes and
   properties of classes
  A facility for specifying mapping metadata
  A technique for the ORM implementation to interact with transactional
   objects to perform dirty checking, lazy association fetching and other
   optimization functions.




© JBoss, Inc. 2003, 2004.                                                              7
PERSISTENCE APPROACH
                                                         Professional Open Source™




 THE BEST FOR THE MOST PROBLEMS
  ORM (Object-Relation Model)

  ORM advantages:

  Productivity - no tedious SQL code

  Maintainability - Fewer lines of code makes the system more
   understandable

  Performance

  Vendor Independence



© JBoss, Inc. 2003, 2004.                                                            8
Analyzing the business domain
                                                                            Professional Open Source™


  A software development effort begins with analysis of the problem domain


  At this stage, you, with the help of problem domain experts, identify the main
  entities that are relevant to the software system. Entities are usually notions
  understood by users of the system: payment, customer, order, item, bid, and so
  forth.


  All these entities are found in the conceptual view of the business, which we
   sometimes call a business model.

  Developers and architects of object-oriented software analyze the business model and
   create an object-oriented model, still at the conceptual level (no Java code). This
   model may be as simple as a mental image existing only in the mind of the developer,
   or it may be as elaborate as a UML class diagram




© JBoss, Inc. 2003, 2004.                                                                               9
What is Domain model ?
                                                              Professional Open Source™


  Object Oriented model contains entities that you’re bound to find in
   any typical system: category, item, and user. The entities and their
   relationships (and perhaps their attributes) are all represented by this
   model of the problem domain.

  We call this kind of object-oriented model of entities from the problem
   domain, encompassing only those entities that are of interest to the
   user, a domain model. It’s an abstract view of the real world.

  The domain model is a rich object model, with complex associations,
  interactions, and inheritance relationships




© JBoss, Inc. 2003, 2004.                                                                 10
Persistence classes of a domain model and their relationships
                                                             Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                                11
Implementing the domain model
                                                           Professional Open Source™


  An issue that any implementation will deal with is Separation of
   concerns

  The domain model implementation is usually a central, organizing
  component; it’s reused heavily whenever you implement new
   application functionality.

  So, u have to ensure that concerns other than business aspects
   don’t leak into the domain model implementation.




© JBoss, Inc. 2003, 2004.                                                              12
Addressing leakage of concerns
                                                            Professional Open Source™


  The domain model implementation is such an important piece of code
   that it shouldn’t depend on orthogonal Java APIs. For example, code
   in the domain model shouldn’t perform JNDI lookups or call the
   database via the JDBC API. This allows you to reuse the domain
   model implementation virtually anywhere.

  Domain model should be concerned only with modeling the
  business domain. However, there are other concerns, such as
   persistence, transaction management, and authorization. You
   shouldn’t put code that addresses these crosscutting concerns in the
   classes that implement the domain model. When these concerns start
   to appear in the domain model classes, this is an example of
  leakage of concerns.

  Hibernate is a solution for just one of these concerns: persistence


© JBoss, Inc. 2003, 2004.                                                               13
Transparent and automated persistence
                                                            Professional Open Source™


  We use transparent to mean a complete separation of concerns
   between the persistent classes of the domain model and the
   persistence logic, where the persistent classes are unaware of—and
   have no dependency on—the persistence mechanism
  The Item class, for example, doesn’t have any code-level
   dependency on any Hibernate API. Furthermore:
    – Hibernate doesn’t require that any special super classes or
      interfaces be inherited or implemented by persistent classes.
    – Persistent classes can be reused outside the context of
      persistence, in unit tests or in the user interface (UI) tier, for
      example.
    – In a system with transparent persistence, objects aren’t aware of
      the underlying data store; they need not even be aware that they
      are being persisted or retrieved. Persistence concerns are
      externalized to a generic persistence manager interface—in the
      case of Hibernate, the Session and Query

© JBoss, Inc. 2003, 2004.                                                               14
Domain Model and the paradigm mismatch
                                                                       Professional Open Source™


  Classes implement the business entities of our domain model
           – attributes of the entity are properties of our Java class
           – associations between entities are also implemented with properties


                                                         BillingDetails
                            User
                                                      accountNumber: String
            userName: String         1        1..*
                                                      accountName: String
            address: String
                                                      accountType: String
            billingDetails: Set
                                                      user: User




        Let’s see if there is a problem mapping this to tables and columns...




© JBoss, Inc. 2003, 2004.                                                                          15
Creating tables for the Domain Model
                                                                       Professional Open Source™


  SQL schema design for trivial cases is ... trivial:

                   create table USER (
                       USER_NAME       varchar not null primary key,
                       ADDRESS         varchar not null)

                   create table BILLING_DETAILS (
                       ACCOUNT_NUMBER varchar not null primary key,
                       ACCOUNT_NAME   varchar not null,
                       ACCOUNT_TYPE   varchar not null,
                       USER_NAME      varchar foreign key references USER)




     We’ll see the 5 problems of the O/R paradigm mismatch appear as we
                    gradually make our model more complex…




© JBoss, Inc. 2003, 2004.                                                                          16
The problem of granularity
                                                                      Professional Open Source™



                                                              Address
                            User
                                                          street: String
               userName: String
                                                          city: String
               billingDetails: Set
                                                          zipcode: String



           – should we create a new ADDRESS table?
           – should we create a new SQL data type and change the column?
           – user-defined data types (UDT) are not portable and the standard is weak


  We usually add new columns to USER with built-in SQL data types:

                create table USER (
                    USER_NAME           varchar   not   null primary key,
                    ADDRESS_STREET      varchar   not   null,
                    ADDRESS_CITY        varchar   not   null,
                    ADDRESS_ZIPCODE     varchar   not   null)


© JBoss, Inc. 2003, 2004.                                                                         17
The problem of subtypes
                                                                     Professional Open Source™


  We create subclasses of BillingDetails:

                                   1      1..*
                            User                    BillingDetails




                                       CreditCard                    Cheque

  and use polymorphism in Java to implement our billing strategy.



                    How do we represent subtypes in our relational model?




© JBoss, Inc. 2003, 2004.                                                                        18
The problem of identity
                                                                              Professional Open Source™


  In Java, we have two notions of "sameness"
           •      object identity is the memory location of an object, a==b
           •      object equality (what is this really?), a.equals(b)


  In SQL databases, we identify a particular row using the primary key
   and the table name. Often, this is a (meaningless) surrogate key!




     What is the relationship between the three different types of identity in
      our domain model? Is the surrogate key propagated into the domain
                                     model?




© JBoss, Inc. 2003, 2004.                                                                                 19
The problem of associations
                                                                          Professional Open Source™


  Object-oriented languages represent entity relationships as
           object references (pointers) and collections of object references


  Relational databases represent entity relationships as
           – copies of primary key values
           – referential integrity ensured by foreign key constraints


  The mismatch:
           – object references are directional, there is no such concept in the relational
             model
           – many-to-many associations require a link table in relational databases




© JBoss, Inc. 2003, 2004.                                                                             20
The problem of object graph navigation
                                                                           Professional Open Source™


  In Java, we "walk" the object graph by following references:
           david.getBillingDetails().getAccountName()


  In SQL, we join tables to get the required data:
           select * from USER u
               left outer join BILLING_DETAILS bd
               on bd.USER_ID = u.USER_ID
               where u.USERNAME = “david"




                            Avoid the n+1 selects problem by minimizing the SQL
                                         required for graph walking!




© JBoss, Inc. 2003, 2004.                                                                              21
The cost of the mismatch
                                                                            Professional Open Source™


  There problems can, at least theoretically, be solved using
   handwritten SQL/JDBC
           –     by writing a lot of tedious code (maybe 30% of your codebase)
           –     The “mismatch problem” is real
           –     better UDT support in SQL will not solve all the issues
           –     not all applications are suitable for table-oriented approaches




                                Is the solution design patterns (DAO)
                            or programming models (EJB entity beans)?

       "How should we implement the persistence layer in our application?"




© JBoss, Inc. 2003, 2004.                                                                               22
Object/Relational Mapping
                                                                      Professional Open Source™


  Object / Relational Mapping (ORM)
           – solve the mismatch problem in middleware
           – an ORM solution transforms data from the object-oriented representation
             to the relational representation
           – metadata governs this transformation

  Elements of an ORM implementation
           –     a programming model for the domain objects
           –     an API for performing CRUD operations
           –     a query language or other query facility
           –     a metadata facility




© JBoss, Inc. 2003, 2004.                                                                         23
Implementing POJO associations
                                                            Professional Open Source™


  You use properties to express associations between POJO
  classes, and you use accessor methods to navigate from
  object to object at runtime.

  Let’s consider the associations defined by
  the Category class, as shown in the figure:
         This is what the scaffolding code for the one-to-many self-
         association of Category looks like:
             public class Category {
                 private String name;
                 private Category parentCategory;
                 private Set childCategories = new HashSet();
                 public Category() { }
                 ...
             }
© JBoss, Inc. 2003, 2004.                                                               24
Implementing POJO associations
                                                             Professional Open Source™


  To allow bidirectional navigation of the association, you require two
   attributes. The parentCategory field implements the single-valued end
   of the association and is declared to be of type Category. The many-
   valued end, implemented by the childCategories field, must be of
   collection type. You choose a Set, because duplicates are disallowed,
   and initialize the instance variable to a new instance of HashSet.

  Hibernate requires interfaces for collection-typed attributes, so you
   must use java.util.Set or java.util.List rather than HashSet, for
   example.
  The basic procedure for adding a child Category to a parent Category
   looks like this:
           –     Category aParent = new Category();
           –     Category aChild = new Category();
           –     aChild.setParentCategory(aParent);
           –     aParent.getChildCategories().add(aChild);


© JBoss, Inc. 2003, 2004.                                                                25
Implementing POJO Associations
                                                                                Professional Open Source™


  Whenever a link is created between a parent Category and a child
   Category, two actions are required:
           – The parentCategory of the child must be set, effectively breaking the association
             between the child and its old parent (there can only be one parent for any child).
           – The child must be added to the childCategories collection of the new parent
             Category.
  It’s a good idea to add a convenience method to the Category class
   that groups these operations, allowing reuse and helping ensure
   correctness, and in the end guarantee data integrity:




© JBoss, Inc. 2003, 2004.                                                                                   26
Adding logic to accessor methods
                                                           Professional Open Source™


  For example, if your database stores the name of a user as a single
   NAME column, but your User class has firstname and lastname
   properties, you can add the following persistent name property to the
   class:




© JBoss, Inc. 2003, 2004.                                                              27
Performing validation in Accessor Method
                                                          Professional Open Source™


  Accessor methods can also perform validation. For instance, in the
   following example, the setFirstName() method verifies that the name
   is capitalized:




© JBoss, Inc. 2003, 2004.                                                             28
Dirty Checking issue
                                                           Professional Open Source™


  Hibernate automatically detects object state changes in order to
   synchronize the updated state with the database. It’s usually safe to
   return a different object from the getter method than the object
   passed by Hibernate to the setter. Hibernate compares the objects
   by
  value—not by object identity—to determine whether the property’s
   persistent state needs to be updated. For example, the following
   getter method doesn’t result in unnecessary SQL UPDATEs:
           –     public String getFirstname() {
           –     return new String(firstname);
           –     }
  There is one important exception to this: Collections are compared
   by identity!
  For a property mapped as a persistent collection, you should return
   exactly the same collection instance from the getter method that
   Hibernate passed to the setter method. If you don’t, Hibernate will
   update the database, even if no update is necessary, every time the
   state held in memory is synchronized with the database.
© JBoss, Inc. 2003, 2004.                                                              29

More Related Content

PDF
5 - Architetture Software - Metamodelling and the Model Driven Architecture
PDF
Introduction to Java EE (J2EE)
PDF
BPMS Buyer's Tool Kit - Sample RFP
PPTX
Chapter2 j2ee
PPT
PPT
15 jpaql
5 - Architetture Software - Metamodelling and the Model Driven Architecture
Introduction to Java EE (J2EE)
BPMS Buyer's Tool Kit - Sample RFP
Chapter2 j2ee
15 jpaql

What's hot (19)

PDF
4 - Architetture Software - Architecture Portfolio
PDF
Paper 55 final
PPT
26 standards
PPT
Introduction to MDA
PPS
Ajs 2 a
PPT
M05 Metamodel
PDF
Building Enterprise Application with J2EE
PDF
A dynamic application using jboss
PDF
Presenter manual J2EE (specially for summer interns)
PPS
Ajs 2 c
PPTX
Model driven architecture
PDF
Model Driven Architecture (MDA): Motivations, Status & Future
PPT
PDF
Solution de génération de rapport OpenDocument à partir de plusieurs sources ...
PDF
MoDisco EclipseCon2010
PDF
Impact Analysis - ImpactScale: Quantifying Change Impact to Predict Faults in...
PPS
Ajs 3 c
PDF
4 - Architetture Software - Architecture Portfolio
Paper 55 final
26 standards
Introduction to MDA
Ajs 2 a
M05 Metamodel
Building Enterprise Application with J2EE
A dynamic application using jboss
Presenter manual J2EE (specially for summer interns)
Ajs 2 c
Model driven architecture
Model Driven Architecture (MDA): Motivations, Status & Future
Solution de génération de rapport OpenDocument à partir de plusieurs sources ...
MoDisco EclipseCon2010
Impact Analysis - ImpactScale: Quantifying Change Impact to Predict Faults in...
Ajs 3 c
Ad

Viewers also liked (6)

PPT
Object oriented sad-5 part ii
PDF
Brief Introduction to Domain Modeling
PPT
Clipping
DOC
Student information-system-project-outline
PPTX
System Analysis and Design
RTF
Project report-on-student-information-management-system-php-mysql
Object oriented sad-5 part ii
Brief Introduction to Domain Modeling
Clipping
Student information-system-project-outline
System Analysis and Design
Project report-on-student-information-management-system-php-mysql
Ad

Similar to 01 persistence and domain modeling (20)

PPT
06 association of value types
PPT
Spring ppt
PPTX
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
PPTX
Java ppt.pptxkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Top Java OOP Principles You Should Know Before Your Next Interview
PDF
Spring Framework Tutorial | VirtualNuggets
PDF
PPTX
Spring framework
PPT
Unit 1- Basic concept of object-oriented-programming.ppt
KEY
Practical OOP In Java
PDF
Framework adoption for java enterprise application development
PDF
Elements of DDD with ASP.NET MVC & Entity Framework Code First
PPTX
Java Modularity with OSGi
PDF
Hibernate Interview Questions
PDF
Hibernate reference1
PDF
Object Orientation Fundamentals
PDF
What is Object-Oriented Programming (OOP) and Why Do We Need It?
PDF
The Power of Enterprise Java Frameworks
PPTX
Introduction to Spring & Spring BootFramework
PDF
Spring presentecion isil
06 association of value types
Spring ppt
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java ppt.pptxkkkkkkkkkkkkkkkkkkkkkkkkkkk
Top Java OOP Principles You Should Know Before Your Next Interview
Spring Framework Tutorial | VirtualNuggets
Spring framework
Unit 1- Basic concept of object-oriented-programming.ppt
Practical OOP In Java
Framework adoption for java enterprise application development
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Java Modularity with OSGi
Hibernate Interview Questions
Hibernate reference1
Object Orientation Fundamentals
What is Object-Oriented Programming (OOP) and Why Do We Need It?
The Power of Enterprise Java Frameworks
Introduction to Spring & Spring BootFramework
Spring presentecion isil

More from thirumuru2012 (14)

PPT
15 jpa introduction
PPT
PPT
14 criteria api
PPT
13 caching latest
PPT
12 hibernate int&cache
PPT
12 global fetching strategies
PPT
11 transitive persistence and filters
PPT
10 conversations new
PPT
09 transactions new1
PPT
09 transactions new
PPT
07 association of entities
PPT
05 inheritance
PPT
04 dataaccess
PPT
02 hibernateintroduction
15 jpa introduction
14 criteria api
13 caching latest
12 hibernate int&cache
12 global fetching strategies
11 transitive persistence and filters
10 conversations new
09 transactions new1
09 transactions new
07 association of entities
05 inheritance
04 dataaccess
02 hibernateintroduction

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Cloud computing and distributed systems.
PDF
cuic standard and advanced reporting.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
KodekX | Application Modernization Development
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Advanced methodologies resolving dimensionality complications for autism neur...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Machine learning based COVID-19 study performance prediction
“AI and Expert System Decision Support & Business Intelligence Systems”
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Network Security Unit 5.pdf for BCA BBA.
Diabetes mellitus diagnosis method based random forest with bat algorithm
Cloud computing and distributed systems.
cuic standard and advanced reporting.pdf
Big Data Technologies - Introduction.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KodekX | Application Modernization Development
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation theory and applications.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Empathic Computing: Creating Shared Understanding
The Rise and Fall of 3GPP – Time for a Sabbatical?
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Profit Center Accounting in SAP S/4HANA, S4F28 Col11

01 persistence and domain modeling

  • 1. Professional Open Source™ Persistence and Domain Modelling © JBoss, Inc. 2003, 2004. 07/17/04 1
  • 2. The persistence layer Professional Open Source™  How does the Java application interact with the SQL database?  Application layers – group related code by concern – prevent leakage of concerns – have clear interfaces to avoid inter-layer dependencies  A typical Layered Architecture and its interface dependencies: Presentation Layer Utility and Business Layer Helper Classes Persistence Layer © JBoss, Inc. 2003, 2004. 2
  • 3. What is persistence? Professional Open Source™  “Persistence” – where data (state) outlives the process that created it  In object-oriented applications: – objects in a system are by default transient – some of the objects in the graph are made persistent – this subgraph of persistent instances can later be re-created in the same process or another process  We need a data model and data store for persistent data...  The Relational Data Model and  SQL-based Database Management Systems. © JBoss, Inc. 2003, 2004. 3
  • 4. PERSISTENCE APPROACHES Professional Open Source™  1. A well-know and widely used DAO design pattern to wide complex  JDBC code and no portable SQL from business logic.  ORM also uses DAO pattern © JBoss, Inc. 2003, 2004. 4
  • 5. PERSISTENCE APPROACHES Professional Open Source™  2. EJB entity beans (CMP)  Not fully object-oriented   Doesn’t support polymorphic associations and queries   Not portable across application servers  Persistence runs only with EJB container  In EJB3 no CMP, uses ORM for persistence  Hibernate is good for JBOSS and major app. Servers  Top Link is good for Oracle app. server © JBoss, Inc. 2003, 2004. 5
  • 6. PERSISTENCE APPROACHES Professional Open Source™  3. Object-oriented database system (ODBMS)  JDO (Java Data Objects) are popular.  But, object-databases are not widely adopted. © JBoss, Inc. 2003, 2004. 6
  • 7. PERSISTENCE APPROACH Professional Open Source™ 4. THE BEST FOR THE MOST PROBLEMS  ORM (Object-Relation Model)  An API for performing basic CRUD operations on objects of persistent classes  A language or API for specifying queries that refer to classes and properties of classes  A facility for specifying mapping metadata  A technique for the ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching and other optimization functions. © JBoss, Inc. 2003, 2004. 7
  • 8. PERSISTENCE APPROACH Professional Open Source™ THE BEST FOR THE MOST PROBLEMS  ORM (Object-Relation Model)  ORM advantages:  Productivity - no tedious SQL code  Maintainability - Fewer lines of code makes the system more understandable  Performance  Vendor Independence © JBoss, Inc. 2003, 2004. 8
  • 9. Analyzing the business domain Professional Open Source™  A software development effort begins with analysis of the problem domain  At this stage, you, with the help of problem domain experts, identify the main  entities that are relevant to the software system. Entities are usually notions  understood by users of the system: payment, customer, order, item, bid, and so  forth.  All these entities are found in the conceptual view of the business, which we sometimes call a business model.  Developers and architects of object-oriented software analyze the business model and create an object-oriented model, still at the conceptual level (no Java code). This model may be as simple as a mental image existing only in the mind of the developer, or it may be as elaborate as a UML class diagram © JBoss, Inc. 2003, 2004. 9
  • 10. What is Domain model ? Professional Open Source™  Object Oriented model contains entities that you’re bound to find in any typical system: category, item, and user. The entities and their relationships (and perhaps their attributes) are all represented by this model of the problem domain.  We call this kind of object-oriented model of entities from the problem domain, encompassing only those entities that are of interest to the user, a domain model. It’s an abstract view of the real world.  The domain model is a rich object model, with complex associations,  interactions, and inheritance relationships © JBoss, Inc. 2003, 2004. 10
  • 11. Persistence classes of a domain model and their relationships Professional Open Source™ © JBoss, Inc. 2003, 2004. 11
  • 12. Implementing the domain model Professional Open Source™  An issue that any implementation will deal with is Separation of concerns  The domain model implementation is usually a central, organizing  component; it’s reused heavily whenever you implement new application functionality.  So, u have to ensure that concerns other than business aspects don’t leak into the domain model implementation. © JBoss, Inc. 2003, 2004. 12
  • 13. Addressing leakage of concerns Professional Open Source™  The domain model implementation is such an important piece of code that it shouldn’t depend on orthogonal Java APIs. For example, code in the domain model shouldn’t perform JNDI lookups or call the database via the JDBC API. This allows you to reuse the domain model implementation virtually anywhere.  Domain model should be concerned only with modeling the  business domain. However, there are other concerns, such as persistence, transaction management, and authorization. You shouldn’t put code that addresses these crosscutting concerns in the classes that implement the domain model. When these concerns start to appear in the domain model classes, this is an example of  leakage of concerns.  Hibernate is a solution for just one of these concerns: persistence © JBoss, Inc. 2003, 2004. 13
  • 14. Transparent and automated persistence Professional Open Source™  We use transparent to mean a complete separation of concerns between the persistent classes of the domain model and the persistence logic, where the persistent classes are unaware of—and have no dependency on—the persistence mechanism  The Item class, for example, doesn’t have any code-level dependency on any Hibernate API. Furthermore: – Hibernate doesn’t require that any special super classes or interfaces be inherited or implemented by persistent classes. – Persistent classes can be reused outside the context of persistence, in unit tests or in the user interface (UI) tier, for example. – In a system with transparent persistence, objects aren’t aware of the underlying data store; they need not even be aware that they are being persisted or retrieved. Persistence concerns are externalized to a generic persistence manager interface—in the case of Hibernate, the Session and Query © JBoss, Inc. 2003, 2004. 14
  • 15. Domain Model and the paradigm mismatch Professional Open Source™  Classes implement the business entities of our domain model – attributes of the entity are properties of our Java class – associations between entities are also implemented with properties BillingDetails User accountNumber: String userName: String 1 1..* accountName: String address: String accountType: String billingDetails: Set user: User Let’s see if there is a problem mapping this to tables and columns... © JBoss, Inc. 2003, 2004. 15
  • 16. Creating tables for the Domain Model Professional Open Source™  SQL schema design for trivial cases is ... trivial: create table USER ( USER_NAME varchar not null primary key, ADDRESS varchar not null) create table BILLING_DETAILS ( ACCOUNT_NUMBER varchar not null primary key, ACCOUNT_NAME varchar not null, ACCOUNT_TYPE varchar not null, USER_NAME varchar foreign key references USER) We’ll see the 5 problems of the O/R paradigm mismatch appear as we gradually make our model more complex… © JBoss, Inc. 2003, 2004. 16
  • 17. The problem of granularity Professional Open Source™ Address User street: String userName: String city: String billingDetails: Set zipcode: String – should we create a new ADDRESS table? – should we create a new SQL data type and change the column? – user-defined data types (UDT) are not portable and the standard is weak  We usually add new columns to USER with built-in SQL data types: create table USER ( USER_NAME varchar not null primary key, ADDRESS_STREET varchar not null, ADDRESS_CITY varchar not null, ADDRESS_ZIPCODE varchar not null) © JBoss, Inc. 2003, 2004. 17
  • 18. The problem of subtypes Professional Open Source™  We create subclasses of BillingDetails: 1 1..* User BillingDetails CreditCard Cheque  and use polymorphism in Java to implement our billing strategy.  How do we represent subtypes in our relational model? © JBoss, Inc. 2003, 2004. 18
  • 19. The problem of identity Professional Open Source™  In Java, we have two notions of "sameness" • object identity is the memory location of an object, a==b • object equality (what is this really?), a.equals(b)  In SQL databases, we identify a particular row using the primary key and the table name. Often, this is a (meaningless) surrogate key! What is the relationship between the three different types of identity in our domain model? Is the surrogate key propagated into the domain model? © JBoss, Inc. 2003, 2004. 19
  • 20. The problem of associations Professional Open Source™  Object-oriented languages represent entity relationships as object references (pointers) and collections of object references  Relational databases represent entity relationships as – copies of primary key values – referential integrity ensured by foreign key constraints  The mismatch: – object references are directional, there is no such concept in the relational model – many-to-many associations require a link table in relational databases © JBoss, Inc. 2003, 2004. 20
  • 21. The problem of object graph navigation Professional Open Source™  In Java, we "walk" the object graph by following references: david.getBillingDetails().getAccountName()  In SQL, we join tables to get the required data: select * from USER u left outer join BILLING_DETAILS bd on bd.USER_ID = u.USER_ID where u.USERNAME = “david" Avoid the n+1 selects problem by minimizing the SQL required for graph walking! © JBoss, Inc. 2003, 2004. 21
  • 22. The cost of the mismatch Professional Open Source™  There problems can, at least theoretically, be solved using handwritten SQL/JDBC – by writing a lot of tedious code (maybe 30% of your codebase) – The “mismatch problem” is real – better UDT support in SQL will not solve all the issues – not all applications are suitable for table-oriented approaches Is the solution design patterns (DAO) or programming models (EJB entity beans)? "How should we implement the persistence layer in our application?" © JBoss, Inc. 2003, 2004. 22
  • 23. Object/Relational Mapping Professional Open Source™  Object / Relational Mapping (ORM) – solve the mismatch problem in middleware – an ORM solution transforms data from the object-oriented representation to the relational representation – metadata governs this transformation  Elements of an ORM implementation – a programming model for the domain objects – an API for performing CRUD operations – a query language or other query facility – a metadata facility © JBoss, Inc. 2003, 2004. 23
  • 24. Implementing POJO associations Professional Open Source™  You use properties to express associations between POJO  classes, and you use accessor methods to navigate from  object to object at runtime.  Let’s consider the associations defined by  the Category class, as shown in the figure: This is what the scaffolding code for the one-to-many self- association of Category looks like: public class Category { private String name; private Category parentCategory; private Set childCategories = new HashSet(); public Category() { } ... } © JBoss, Inc. 2003, 2004. 24
  • 25. Implementing POJO associations Professional Open Source™  To allow bidirectional navigation of the association, you require two attributes. The parentCategory field implements the single-valued end of the association and is declared to be of type Category. The many- valued end, implemented by the childCategories field, must be of collection type. You choose a Set, because duplicates are disallowed, and initialize the instance variable to a new instance of HashSet.  Hibernate requires interfaces for collection-typed attributes, so you must use java.util.Set or java.util.List rather than HashSet, for example.  The basic procedure for adding a child Category to a parent Category looks like this: – Category aParent = new Category(); – Category aChild = new Category(); – aChild.setParentCategory(aParent); – aParent.getChildCategories().add(aChild); © JBoss, Inc. 2003, 2004. 25
  • 26. Implementing POJO Associations Professional Open Source™  Whenever a link is created between a parent Category and a child Category, two actions are required: – The parentCategory of the child must be set, effectively breaking the association between the child and its old parent (there can only be one parent for any child). – The child must be added to the childCategories collection of the new parent Category.  It’s a good idea to add a convenience method to the Category class that groups these operations, allowing reuse and helping ensure correctness, and in the end guarantee data integrity: © JBoss, Inc. 2003, 2004. 26
  • 27. Adding logic to accessor methods Professional Open Source™  For example, if your database stores the name of a user as a single NAME column, but your User class has firstname and lastname properties, you can add the following persistent name property to the class: © JBoss, Inc. 2003, 2004. 27
  • 28. Performing validation in Accessor Method Professional Open Source™  Accessor methods can also perform validation. For instance, in the following example, the setFirstName() method verifies that the name is capitalized: © JBoss, Inc. 2003, 2004. 28
  • 29. Dirty Checking issue Professional Open Source™  Hibernate automatically detects object state changes in order to synchronize the updated state with the database. It’s usually safe to return a different object from the getter method than the object passed by Hibernate to the setter. Hibernate compares the objects by  value—not by object identity—to determine whether the property’s persistent state needs to be updated. For example, the following getter method doesn’t result in unnecessary SQL UPDATEs: – public String getFirstname() { – return new String(firstname); – }  There is one important exception to this: Collections are compared by identity!  For a property mapped as a persistent collection, you should return exactly the same collection instance from the getter method that Hibernate passed to the setter method. If you don’t, Hibernate will update the database, even if no update is necessary, every time the state held in memory is synchronized with the database. © JBoss, Inc. 2003, 2004. 29