SlideShare a Scribd company logo
J2EE Data Access Objects
                         A brief article for developers
                            Prepared By Owen Taylor
The Data Access Object Pattern
  In this paper, we will discuss the popular J2EE Design Pattern known as the Data Access
  Object Pattern. The article is useful for people who may not have time to read a whole book,
  but may be interested in learning about a snippet of knowledge as they find the time.

Motivation
  In the J2EE world, there are different specifications and mechanisms for accessing persistent
  storage and legacy data. In an Enterprise JavaBeans application, the data source access
  code might be in a Session Bean or an Entity Bean. In a Web application, the code might be
  in a servlet or a helper class for a JSP.
  If data access is coded directly into business components, the components become tightly
  coupled to the data source. This happens for a variety of reasons:
     •   Persistent storage APIs vary, depending on the vendor
     •   Some APIs may be completely proprietary
     •   With JDBC, SQL statements may vary according to the database product
  Because of this, often times if the data source changes, the components must change as
  well. Furthermore, coding data access directly into components also limits reuse of the data
  access code.
  To make J2EE applications flexible, it is good practice to factor data access out of business
  components. A way must be found to abstract business logic from detailed knowledge of
  where the data resides and how it should be managed.

Solution
  The Data Access Object (DAO) pattern separates the access to a data source the business
  components. Business components are no longer coupled to a specific vendor
  implementation or API. Application developers can control how data is accessed; if a vendor
  or an API changes later, the DataAccessObject is the only code that needs to change.
  A DAO has two main functions:
     •   The DAO contains logic to access a data source
     •   The DAO manages the connection to the data source to obtain and store data




                                                                                                  1
A DAO is used by a business component. The DAO access the underlying data source, and
  returns results back to the business component. The data that is sent back and forth
  between a business component and a DAO are encapsulated inside of another special object
  that we will call a Data Transfer Object (DTO), also commonly known as a value object (VO).

Structure
  The following class diagram shows the relationships for the Data Access Object Pattern. The
  DataAccessObject (DAO) encapsulates access to the DataSource and acts as a factory and
  manager for Data Transfer Objects.




                                                                                            2
The following sequence diagram shows the interaction among the participants in the Data
Access Object pattern. The BusinessObject creates the DataAccessObject and uses it to get
data. The DataAccessObject encapsulates access to a DataSource. The Data Access
Object also manages creation of and updates to data in the DataSource. A Data Access
Object consists of getter and setter methods to manipulate the data.




As you can see, the DAO is responsible for creating Data Transfer Objects (DTOs), which are
convenient means to pass data between BusinessObjects and DAOs. Once the
BusinessObject completes processing of the DTO, it can return the DTO to the DAO. The
DAO can write the changes out to the DataSource to complete the transaction.




                                                                                         3
Sample Code
    The following code example will illustrate an implementation of the Data Access Object
    pattern. For brevity, the code example will not include data source access or JDBC examples.
    The object model we will use is an inventory tracking system.

The Data Transfer Object (DTO) code
    The first class is an Item which is a Data Transfer Object that the DAO can return or
    manipulate to make changes to the data source.

//Item.java

package com.test;

public class Item {

         private String name;
         private int count;
         private float cost;

         public    String getItemName() { … }
         public    void setItemName(String name) { … }
         public    int getItemCount() { … }
         public    void setItemName(int count) { … }
         public    float getItemCost() { … }
         public    void setItemCost(float cost) { … }
}




                                                                                              4
The exception class code
    We will also create an exception class to encapsulate any kind of data access difficulty.

//DataAccessException.java

package com.test;

public class DataAccessException extends Exception {
   Throwable whyException;

     public DataAccessException(String message){
       super(message);
     }

     public DataAccessException(String message, Throwable t){
       super(message);
       this.whyException = t;
     }

     public void printStackTrace(){
       if(! (whyException==null)){
         System.err.println("DATA ACCESS ISSUE: ");
         whyException.printStackTrace();
       }
     }
}

The Data Access Object (DAO) interface code
    The following interface will be implemented by all concrete implementations of the Inventory
    DAO. The implementations are responsible for managing resources (connections) and
    reading and writing data. The interface ties all implementations together with a single type.
    This is convenient if we decide to use a factory to create or access Inventory DAOs.

//InventoryDAO.java

package com.test;

public interface InventoryDAO {

         public Collection getAllItems()throws DataAccessException;

         public void addItem(Item i) throws DataAccessException;

     public void removeItem(Item i) throws DataAccessException;
}//end of InventoryDAO interface




                                                                                                    5
The Data Access Object (DAO) implementation code
 Our DAO implementation, JDBCInventoryDAO, is a simple implementation of the
 InventoryDAO interface.

//JDBCInventoryDAO.java

package com.test;

import java.sql.*;
import java.util.*;

public class JDBCInventoryDAO implements InventoryDAO {
     public JDBCInventoryDAO() {
       // Initialize access to the database (not shown)
     }
     public Collection getAllItems() throws DataAccessException{
       //JDBC Access code not shown
     }
     public void addItem(Item I) throws DataAccessException{
       //JDBC Insert code not shown
     }
     public void removeItem(Item I) throws DataAccessException{
       //JDBC Delete code not shown
     }
}




                                                                               6
The client code
  Because we are implementing a solution within the context of J2EE, our client is shown as an
  EJB Session Bean.
  This simple client illustrates how to use a DAO. Notice that the client is completely
  abstracted from any data source implementation details. The client does not have to import
  any data source specific packages and simply creates a DAO to access items.

//InventoryClient.java

package com.test;
import java.util.*;
import java.ejb.*;

public class InventoryClientBean implements SessionBean {

      /*    Code required to be a SessionBean not shown. . .*/

  public void WorkWithInventory() {
    try {
      InventoryDAO dao = new JDBCInventoryDAO();
      Collection items = dao.getAllItems();
      // do something with the items
    }

    catch (DataAccessException dae) {
           //handle the exception
    }
  }
}//end of InventoryClientBean




                                                                                               7
Summary
  By defining an interface InventoryDAO we have defined a specific context within which all of
  the DAO implementations must be created. The more specific our context, the easier it is to
  build and use appropriate implementations, such as:
          •   JDO
          •   JDBC
          •   EJB CMP entity beans
          •   EJB BMP entity beans
  It is always up to the design team on a particular project to determine the breadth of the
  context for both encapsulating business responsibilities and creational responsibilities. In
  anticipation of future changes, we encapsulated the responsibilities within our InventoryDAO
  interface. We are free to implement these responsibilities in any new Objects as we choose.
  (As long as they implement InventoryDAO).
  This pattern illustrates one of our goals as designers, which should be to follow the Open-
  closed principle:
  Design applications so that they can be extended without modification to the existing code.
  They will therefore be:
     •   Open to new features.
     •   Closed to changes in the code.


  In summary, the values of this design pattern are as follows:
     •   Enables persistence transparency
     •   Enables easier migration
     •   Reduces code complexity in Business Objects
     •   Centralizes all data access into a separate layer


  There are a few considerations one should take into account, however:
     •   This pattern is less important when CMP is used, since CMP encapsulates data
         access by definition, unless a legacy system demands it.
     •   Using DAOs adds an extra layer to your application
     •   It requires a somewhat complex class hierarchy design

Related Patterns
     •   Data Transfer Object (or Value Object)
     •   Bridge
     •   Adapter
     •   Factory
     •   Abstract Factory


                                                                                                 8
Closing Thoughts
 This article is one in a series of articles available for download on TheServerSide.com that
 The Middleware Company is making available to Java developers. The Middleware
 Company believes that learning patterns such as the ones discussed in this white paper can
 mean the difference between failure and success when developing J2EE applications.
 Patterns can save time and money and avoid great frustration when used properly. And it
 can also help you…
    •   Increase your value as a Java developer in today's economy
    •   Become a better Enterprise Java programmer
    •   Succeed on that upcoming project
 Teaching you to apply them in the correct context, understand when they can be combined to
 form compound patterns, and recognize anti-patterns is also the goal of a new advanced
 J2EE Patterns course that is available immediately for registration worldwide.
 The J2EE Patterns course is:
    •   An intensive 5-day course, purely on the subject of J2EE Patterns
    •   A hardcore, advanced training course for the seasoned J2EE programmer
    •   Requires knowledge of J2EE programming, and is chock-full of hands-on lab
        exercises where students gain experience programming with J2EE design patterns
 You can learn more about it here:
 http://www.middleware-company.com/training/j2eepatterns.shtml




                                                                                                9
Ad

More Related Content

What's hot (20)

WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
MuthuKumaran Singaravelu
 
Facade Design Pattern
Facade Design PatternFacade Design Pattern
Facade Design Pattern
Livares Technologies Pvt Ltd
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
Basant Medhat
 
React workshop
React workshopReact workshop
React workshop
Imran Sayed
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE Patterns
Emprovise
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
Rajiv Srivastava
 
Spring Boot 3 And Beyond
Spring Boot 3 And BeyondSpring Boot 3 And Beyond
Spring Boot 3 And Beyond
VMware Tanzu
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Tomcat
TomcatTomcat
Tomcat
Venkat Pinagadi
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Steve Pember
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
Abid Kohistani
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptx
FalgunSorathiya
 
Spring Boot and Microservices
Spring Boot and MicroservicesSpring Boot and Microservices
Spring Boot and Microservices
seges
 
Spring batch
Spring batchSpring batch
Spring batch
Chandan Kumar Rana
 
What's new in Android - Google I/O Extended Bangkok 2022
What's new in Android - Google I/O Extended Bangkok 2022What's new in Android - Google I/O Extended Bangkok 2022
What's new in Android - Google I/O Extended Bangkok 2022
Somkiat Khitwongwattana
 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ Coroutines
Sumant Tambe
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
Santosh Kumar Kar
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
Akshay Ballarpure
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
Rajesh Ganesan
 

Similar to Dao pattern (20)

Utilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap IntegrationUtilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap Integration
Guo Albert
 
Dao example
Dao exampleDao example
Dao example
myrajendra
 
Data access
Data accessData access
Data access
Joshua Yoon
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
phanleson
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
myrajendra
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
prabhu rajendran
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE Applications
Buhake Sindi
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Amit Singh
 
Spring 2
Spring 2Spring 2
Spring 2
Aruvi Thottlan
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
 
Spring survey
Spring surveySpring survey
Spring survey
Chris Roeder
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
Thodoris Bais
 
ADO.NET Interview Questions PDF By ScholarHat
ADO.NET  Interview Questions PDF By ScholarHatADO.NET  Interview Questions PDF By ScholarHat
ADO.NET Interview Questions PDF By ScholarHat
Scholarhat
 
Ado
AdoAdo
Ado
actacademy
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
Virtual Nuggets
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc
JdbcJdbc
Jdbc
Yamuna Devi
 
Jdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.comJdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.com
phanleson
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
Michael Heron
 
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
Utilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap IntegrationUtilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap Integration
Guo Albert
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
phanleson
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE Applications
Buhake Sindi
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Amit Singh
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
Thodoris Bais
 
ADO.NET Interview Questions PDF By ScholarHat
ADO.NET  Interview Questions PDF By ScholarHatADO.NET  Interview Questions PDF By ScholarHat
ADO.NET Interview Questions PDF By ScholarHat
Scholarhat
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
Virtual Nuggets
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.comJdbc Dao it-slideshares.blogspot.com
Jdbc Dao it-slideshares.blogspot.com
phanleson
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
Michael Heron
 
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
Ad

Recently uploaded (20)

Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Ad

Dao pattern

  • 1. J2EE Data Access Objects A brief article for developers Prepared By Owen Taylor The Data Access Object Pattern In this paper, we will discuss the popular J2EE Design Pattern known as the Data Access Object Pattern. The article is useful for people who may not have time to read a whole book, but may be interested in learning about a snippet of knowledge as they find the time. Motivation In the J2EE world, there are different specifications and mechanisms for accessing persistent storage and legacy data. In an Enterprise JavaBeans application, the data source access code might be in a Session Bean or an Entity Bean. In a Web application, the code might be in a servlet or a helper class for a JSP. If data access is coded directly into business components, the components become tightly coupled to the data source. This happens for a variety of reasons: • Persistent storage APIs vary, depending on the vendor • Some APIs may be completely proprietary • With JDBC, SQL statements may vary according to the database product Because of this, often times if the data source changes, the components must change as well. Furthermore, coding data access directly into components also limits reuse of the data access code. To make J2EE applications flexible, it is good practice to factor data access out of business components. A way must be found to abstract business logic from detailed knowledge of where the data resides and how it should be managed. Solution The Data Access Object (DAO) pattern separates the access to a data source the business components. Business components are no longer coupled to a specific vendor implementation or API. Application developers can control how data is accessed; if a vendor or an API changes later, the DataAccessObject is the only code that needs to change. A DAO has two main functions: • The DAO contains logic to access a data source • The DAO manages the connection to the data source to obtain and store data 1
  • 2. A DAO is used by a business component. The DAO access the underlying data source, and returns results back to the business component. The data that is sent back and forth between a business component and a DAO are encapsulated inside of another special object that we will call a Data Transfer Object (DTO), also commonly known as a value object (VO). Structure The following class diagram shows the relationships for the Data Access Object Pattern. The DataAccessObject (DAO) encapsulates access to the DataSource and acts as a factory and manager for Data Transfer Objects. 2
  • 3. The following sequence diagram shows the interaction among the participants in the Data Access Object pattern. The BusinessObject creates the DataAccessObject and uses it to get data. The DataAccessObject encapsulates access to a DataSource. The Data Access Object also manages creation of and updates to data in the DataSource. A Data Access Object consists of getter and setter methods to manipulate the data. As you can see, the DAO is responsible for creating Data Transfer Objects (DTOs), which are convenient means to pass data between BusinessObjects and DAOs. Once the BusinessObject completes processing of the DTO, it can return the DTO to the DAO. The DAO can write the changes out to the DataSource to complete the transaction. 3
  • 4. Sample Code The following code example will illustrate an implementation of the Data Access Object pattern. For brevity, the code example will not include data source access or JDBC examples. The object model we will use is an inventory tracking system. The Data Transfer Object (DTO) code The first class is an Item which is a Data Transfer Object that the DAO can return or manipulate to make changes to the data source. //Item.java package com.test; public class Item { private String name; private int count; private float cost; public String getItemName() { … } public void setItemName(String name) { … } public int getItemCount() { … } public void setItemName(int count) { … } public float getItemCost() { … } public void setItemCost(float cost) { … } } 4
  • 5. The exception class code We will also create an exception class to encapsulate any kind of data access difficulty. //DataAccessException.java package com.test; public class DataAccessException extends Exception { Throwable whyException; public DataAccessException(String message){ super(message); } public DataAccessException(String message, Throwable t){ super(message); this.whyException = t; } public void printStackTrace(){ if(! (whyException==null)){ System.err.println("DATA ACCESS ISSUE: "); whyException.printStackTrace(); } } } The Data Access Object (DAO) interface code The following interface will be implemented by all concrete implementations of the Inventory DAO. The implementations are responsible for managing resources (connections) and reading and writing data. The interface ties all implementations together with a single type. This is convenient if we decide to use a factory to create or access Inventory DAOs. //InventoryDAO.java package com.test; public interface InventoryDAO { public Collection getAllItems()throws DataAccessException; public void addItem(Item i) throws DataAccessException; public void removeItem(Item i) throws DataAccessException; }//end of InventoryDAO interface 5
  • 6. The Data Access Object (DAO) implementation code Our DAO implementation, JDBCInventoryDAO, is a simple implementation of the InventoryDAO interface. //JDBCInventoryDAO.java package com.test; import java.sql.*; import java.util.*; public class JDBCInventoryDAO implements InventoryDAO { public JDBCInventoryDAO() { // Initialize access to the database (not shown) } public Collection getAllItems() throws DataAccessException{ //JDBC Access code not shown } public void addItem(Item I) throws DataAccessException{ //JDBC Insert code not shown } public void removeItem(Item I) throws DataAccessException{ //JDBC Delete code not shown } } 6
  • 7. The client code Because we are implementing a solution within the context of J2EE, our client is shown as an EJB Session Bean. This simple client illustrates how to use a DAO. Notice that the client is completely abstracted from any data source implementation details. The client does not have to import any data source specific packages and simply creates a DAO to access items. //InventoryClient.java package com.test; import java.util.*; import java.ejb.*; public class InventoryClientBean implements SessionBean { /* Code required to be a SessionBean not shown. . .*/ public void WorkWithInventory() { try { InventoryDAO dao = new JDBCInventoryDAO(); Collection items = dao.getAllItems(); // do something with the items } catch (DataAccessException dae) { //handle the exception } } }//end of InventoryClientBean 7
  • 8. Summary By defining an interface InventoryDAO we have defined a specific context within which all of the DAO implementations must be created. The more specific our context, the easier it is to build and use appropriate implementations, such as: • JDO • JDBC • EJB CMP entity beans • EJB BMP entity beans It is always up to the design team on a particular project to determine the breadth of the context for both encapsulating business responsibilities and creational responsibilities. In anticipation of future changes, we encapsulated the responsibilities within our InventoryDAO interface. We are free to implement these responsibilities in any new Objects as we choose. (As long as they implement InventoryDAO). This pattern illustrates one of our goals as designers, which should be to follow the Open- closed principle: Design applications so that they can be extended without modification to the existing code. They will therefore be: • Open to new features. • Closed to changes in the code. In summary, the values of this design pattern are as follows: • Enables persistence transparency • Enables easier migration • Reduces code complexity in Business Objects • Centralizes all data access into a separate layer There are a few considerations one should take into account, however: • This pattern is less important when CMP is used, since CMP encapsulates data access by definition, unless a legacy system demands it. • Using DAOs adds an extra layer to your application • It requires a somewhat complex class hierarchy design Related Patterns • Data Transfer Object (or Value Object) • Bridge • Adapter • Factory • Abstract Factory 8
  • 9. Closing Thoughts This article is one in a series of articles available for download on TheServerSide.com that The Middleware Company is making available to Java developers. The Middleware Company believes that learning patterns such as the ones discussed in this white paper can mean the difference between failure and success when developing J2EE applications. Patterns can save time and money and avoid great frustration when used properly. And it can also help you… • Increase your value as a Java developer in today's economy • Become a better Enterprise Java programmer • Succeed on that upcoming project Teaching you to apply them in the correct context, understand when they can be combined to form compound patterns, and recognize anti-patterns is also the goal of a new advanced J2EE Patterns course that is available immediately for registration worldwide. The J2EE Patterns course is: • An intensive 5-day course, purely on the subject of J2EE Patterns • A hardcore, advanced training course for the seasoned J2EE programmer • Requires knowledge of J2EE programming, and is chock-full of hands-on lab exercises where students gain experience programming with J2EE design patterns You can learn more about it here: http://www.middleware-company.com/training/j2eepatterns.shtml 9