Background:
The methods for accessing data vary depending on different data sources. Accessing persistent data sources, such as databases, varies with their storage types (relational databases, object-oriented databases, simple file storage, other methods) is very different from the provider's custom data type.
Problems:
Many put-in-use J2EE Web applications require data persistence in some cases. for many web applications, data persistence storage can be implemented through different mechanisms. The document clearly shows the differences between these APIs used to access different data persistence mechanisms. some other applications may access data resources on a specific system. for example, on the mainframe system, it may also be in the Lightweight Directory Access Protocol LDAP repository, or what other systems. in addition, data may also be provided by external integration system services such as B2B, credit card bureau services, or other services. in general, the program uses some shared distributed components to represent persistent data. for example, Entity Bean. when the Entity Bean in a program accesses persistent data in a direct way, the bean management persistence mode (BMP) will be considered to illustrate the white points, the entity bean in the program contains code for directly accessing persistent data. in another case, the program can use container management for persistence. Instead of writing any code, you need to let the Container Handle the specific details of data persistence.
The program can use the jdbc api to access data in the relational database. it makes it possible to access and process data in a persistent carrier such as a relational database. it also allows J2EE applications to use SQL statements as standard access to relational database statements. however, even in a relational database environment, different database products may cause SQL statements to be used and the syntax and format are different.
For different types of persistent data warehouses, the difference is even greater. access mechanisms, APIs, and some other features are very different because they are relational databases, object-oriented databases, and general files. you need to access the database applications of previous legacy systems or professional systems such as large hosts and B2B, and often use some of your own unique APIs. these special data sources pose great challenges to the compilation of applications, and may cause mutual dependency between program code and data access code. when commercial components such as entity beans, session beans, and servlets and JSP help objects need to access data resources, you can use standard APIs to perform database connection and data operations. however, writing the operation code for connecting to the database and data together with these components will lead to coupling between these components and database operations. This coupling exists, it is very difficult and boring to migrate data from the current data source type to another data source type in the application. if the data source changes, your components have to be changed to adapt to the new data source.
Necessity:
1. components such as bean Management Entity Bean, Session Bean, Servlets, and other JSP Helper Objects usually need to be stored in a persistent database, a legacy system, and B2B, extract or store data in a system such as LDAP.
2 APIs used for persistent storage vary with providers. Some data sources may also have their own unique APIs or some non-standard APIs. Various types of data persistence systems and carriers, such as relational databases, object-oriented database management systems, XML documents, and simple files, make different APIs have different performance. We lack a unified API to operate on different systems or file carriers.
3 components generally use special APIs to access or extract data from internal systems or legacy systems.
4 when some specific access mechanisms and APIs are included in these components, their compatibility will be directly affected.
5. components must be transparent to existing persistent storage systems or data sources, so that they can be migrated to different products, storage systems, and data sources, easy to change.
Solution
Use data access objects to abstract and encapsulate all access to the data source. The Data Access Object is responsible for managing the connection with the data source to obtain and store the data.
Data access objects implement access mechanisms related to data sources. The data source can be a relational database management system, an internal service such as B2B exchange, an LDAP database, or a commercial service accessed through the IIOP or the low-layer sockets. commercial components dependent on Dao only expose some very simple Dao external interfaces to their clients. dao completely hides the implementation details of the data source from the client. because the DaO interface exposed to the client does not change when the implementation of the low-level data source changes, therefore, this design model allows Dao to adapt to different data storage methods without affecting the client and business components. most importantly, Dao also plays the coordinator role between components and data sources.
The following is an explanation of each module in the DAO design mode:
1 businessobject refers to the data client, which usually needs to access the data source to obtain or store data. in addition to accessing the data source servlet or helper bean, A businessobject can also be Session Bean, Entity Bean, and some other Java objects.
2 dataaccessobject is the core part of this design model. dataaccessobject abstracts the details of the underlying data access implementation for businessobject, making the access data transparent. businessobject also delivers data loading and storage to dataaccessobject for proxy.
3. datasource indicates the implementation of the data source. A data source can be a database such as a relational database management system, an object-oriented database management system, an XML document, or a simple file. of course, it can also be other systems (legacy systems, large hosts), services (B2B services, credit card board services) or databases such as LDAP.
4 transferobject: it represents the object to be transmitted, which is generally used as the data carrier. dataaccessobject uses a transfer object to return data to the client. dataaccessobject can also use a transfer object to receive data from the client to update the data in the original database.
Policy:
Since each businessobject has a corresponding Dao, a definite relationship can be established between businessobject, Dao, and the underlying implementation (such as tables in relational databases ). Once the relationship between them is established, we can use a specially customized code generator for this application to generate code involving all DaO of the application. The metadata that generates Dao can also be obtained through the descriptor file customized by the developer. the code generator can also automatically check the database and provide some necessary Dao to access the database according to the actual situation. if Dao requirements are too complex, you need to use third-party tools to provide object-to-link ing for relational databases. these tools generally contain graphical user interfaces that can easily picture commercial objects to persistent objects, so Dao can be defined. These tools can automatically generate code at the end of the Shadow. In addition, they can provide some additional benefits, such as result caching, query caching, and integration with the application server, the sum (Distribution Test cache) of third-party products.
1. Factory Mode Policy:
The DAO design pattern can be very flexible by adopting the abstract factory and factory method pattern.
When the underlying data storage implementation does not need to change, this policy can be implemented using the factory method design mode to generate the DaO required by the application.
When the underlying data storage implementation has to change, we can use the abstract factory mode to implement this policy. just as in the Design Pattern: reusable elements of object-oriented software, this book suggests that abstract factories should be created first and then implemented using factory methods. in the current situation, this policy can provide an abstract Dao factory object (Abstract Factory) and use it to create different types of specific Dao factories ., each factory supports different persistent data storage implementations. once you obtain a specific Dao factory for a specific implementation, you can use this factory to generate the DaO object supported and implemented by that specific implementation.
Advantages and disadvantages:
Benefits of DAO design pattern.
1. Transparency:
Commercial objects can use the data source without knowing how to implement the data source. Access to the data source is transparent because the implementation details have been hidden in Dao.
2. Simplified migration:
The emergence of the DaO layer makes it easy to migrate applications to different databases. business Objects can have no idea about the underlying data implementation. in this way, the migration only involves modifications to the DaO layer. in addition, if a factory policy is used, it is possible to provide a specific factory implementation for each underlying data implementation. in this case, migrating to a different data implementation is equivalent to providing a new factory implementation for this application.
3. Reduce programming difficulty in business objects.
Because Dao manages all the data access details, it greatly simplifies the code in business objects and other data clients that use DAO. all Code related to implementation details, such as SQL statements, are included in Dao and not in commercial objects. this makes the code more robust and greatly improves the development efficiency.
4. Separate all data access into one layer.
Because all data access operations have now been proxy by Dao, this independent data access layer can be seen as a layer that isolates Data Access implementation from other applications. such a set makes it easier to maintain and manage applications.
Disadvantages:
5 useless to container management persistence
Because the EJB container uses CMP (container management persistence) to manage the Entity Bean. the container automatically provides services for persistent storage access. the application uses the container-managed object bean without the DaO layer. because the application server itself can provide these functions transparently. however, Dao is useful when combined CMP and BMP are required.
6. Additional layers are added.
Because Dao creates an object outside the Data Client and data source, it needs to be designed and implemented to balance the advantages and disadvantages of this design mode. however, in general, the adoption of this design pattern is more advantageous than the disadvantage.
7. design the inheritance relationships of classes.
When using factory policies, the inheritance relationships of specific factory classes and products generated by these factory classes need to be designed and implemented. we need to carefully consider whether these paid jobs can produce higher flexibility. using this policy will make the design more complex. However, you can first implement this policy from the factory method mode, and then switch to the abstract factory as needed.
Example description:
Implement factory policies for Dao
1 adopt the factory method design mode
If a DaO factory is only implemented for a database (such as Oracle) and many Dao are created, we will consider adopting the factory method design mode when implementing this policy. assume that the factory class has created some objects such as customerdao, accountdao, and orderdao.
2. Use the abstract factory design model:
If we want to implement this policy for three different types of databases, we can consider adopting the abstract factory design model. suppose. this factory has created a series of Dao for customerdao, accountdao, and orderdao, which applies the implementation of factory methods in the factory class generated in the abstract factory.
Code Description:
The following code illustrates the specific implementation of the DAO design mode:
Taking the abstract factory design pattern as an example to deal with multiple types of databases, the following example only lists the specific implementation of the DAO design pattern of the cloudscape database type, the implementation of DAO design patterns for other types of databases is similar.
1 // abstract class Dao Factory
Public abstract class daofactory {
// List of Dao types supported by the factory
Public static final int cloudscape = 1;
Public static final int Oracle = 2;
Public static final int Sybase = 3;
...
// There will be a method for each DAO that can be
// Created. The concrete factories will have
// Implement these methods.
// All the methods necessary to implement the factory class of the abstract factory. Use these methods to create a specific DAO class.
Public abstract customerdao getcustomerdao ();
Public abstract accountdao getaccountdao ();
Public abstract orderdao getorderdao ();
// Use the static method of this abstract class to create other specific Dao factory classes
Public static daofactory getdaofactory (
Int whichfactory ){
Switch (whichfactory ){
Case cloudscape:
Return new cloudscapedaofactory ();
Case ORACLE:
Return new oracledaofactory ();
Case SYBASE:
Return new sybasedaofactory ();
...
Default:
Return NULL;
}
}
}
2. The following is the implementation of the cloudscape Dao factory class, which implements the connection to this type of database and the methods that must be implemented in the abstract factory class that he inherits, create a specific Dao object in these methods.
// Cloudscape concrete Dao factory implementation
Import java. SQL .*;
Public class cloudscapedaofactory extends daofactory {
Public static final string driver =
"Com. cloudscape. Core. rmijdbcdriver ";
Public static final string dburl =
"JDBC: cloudscape: RMI: // localhost: 1099/corej2eedb ";
// Method to create cloudscape connections
// Establish a cloudscape connection
Public static connection createconnection (){
// Use driver and dburl to create a connection
// Recommend connection pool Implementation/usage
}
// Create a customerdao object. Of course, the returned interface is implemented by this class. Its advantage is that the implementation details are concealed.
Public customerdao getcustomerdao (){
// Cloudscapecustomerdao implements customerdao
Return new cloudscapecustomerdao ();
}
// Create an accountdao object. Of course, an interface implemented by this class is returned. Its advantage is that the implementation details are concealed.
Public accountdao getaccountdao (){
// Cloudscapeaccountdao implements accountdao
Return new cloudscapeaccountdao ();
}
// Create an orderdao object. Of course, an interface implemented by this class is returned. Its advantage is that the implementation details are concealed.
Public orderdao getorderdao (){
// Cloudscapeorderdao implements orderdao
Return new cloudscapeorderdao ();
}
...
}
3. the following code is the specific DAO class implementation interface, that is, the interface implemented by cloudscapecustomerdao (): customerdao. All business methods are defined in this interface.
// Interface that all mermerdaos must support
Public interface customerdao {
Public int insertcustomer (...);
Public Boolean deletecustomer (...);
Public customer findcustomer (...);
Public Boolean updatecustomer (...);
Public rowset selectcustomersrs (...);
Public Collection selectcustomersto (...);
...
}
4. The specific business details and data operation details of the cloudscapecustomerdao class are concealed from the customer data end.
Import java. SQL .*;
Public class cloudscapecustomerdao implements
Customerdao {
Public cloudscapecustomerdao (){
// Initialization
}
// The following methods can use
// Cloudscapedaofactory. createconnection ()
// To get a connection as required
Public int insertcustomer (...){
// Implement insert customer here.
// Return newly created customer number
// Or A-1 on Error
}
Public Boolean deletecustomer (...){
// Implement delete customer here
// Return true on success, false on Failure
}
Public customer findcustomer (...){
// Implement find a customer here using supplied
// Argument values as search criteria
// Return a transfer object if found,
// Return NULL on error or if not found
}
Public Boolean updatecustomer (...){
// Implement update record here using data
// From the customerdata transfer object
// Return true on success, false on failure or
// Error
}
Public rowset selectcustomersrs (...){
// Implement search customers here using
// Supplied criteria.
// Return a rowset.
}
Public Collection selectcustomersto (...){
// Implement search customers here using
// Supplied criteria.
// Alternatively, implement to return a collection
// Of transfer objects.
}
...
}
5. The following code transfers data from the data client to Dao. It is actually a JavaBean;
Public Class Customer implements java. Io. serializable {
// Member variables
Int customernumber;
String name;
String streetaddress;
String city;
...
// Getter and setter methods...
...
}
6. Finally, the application of the customer data end to this design:
...
// Create the required Dao Factory
Daofactory cloudscapefactory =
Daofactory. getdaofactory (daofactory. daocloudscape );
// Create a Dao
Customerdao custdao =
Cloudscapefactory. getcustomerdao ();
// Create a new customer
Int newcustno = custdao. insertcustomer (...);
// Find a customer object. Get the transfer object.
Customer Cust = custdao. findcustomer (...);
// Modify the values in the transfer object.
Cust. setaddress (...);
Cust. setemail (...);
// Update the customer object using the Dao
Custdao. updatecustomer (Cust );
// Delete a customer object
Custdao. deletecustomer (...);
// Select all customers in the same city
Customer criteria = new customer ();
Criteria. setcity ("New York ");
Collection customerslist =
Custdao. selectcustomersto (criteria );
// Returns customerslist-collection of customer
// Transfer objects. iterate through this collection
// Get values.
1. Create an abstract factory class. It consists of two important parts: The first part is some abstract methods which must be implemented by all the specific factory classes that implement the abstract factory. the second part is a static method, which creates a factory object for a specific type of data source, such as cloudscapedaofactory () in the text ().
2. Create the factory classes for each data source respectively (this article takes cloudscapedaofactory as an example ). there are also two important components in this factory class: The first part is to implement the Left and Right abstract methods in the abstract factory class that he inherits, create a specific Dao object in this method (the classes of these objects are not defined in 4th). In this article, three methods create three specific Dao objects respectively, of course, to conceal the implementation details, these methods return the interfaces implemented by these specific Dao classes (these interfaces are implemented in step 1 ).
3. define the specific Dao interface and define all business methods and data operation methods in the interface.
4. define a specific DAO class. In this class, the actual business methods and data operations are implemented.
5. Define a data transmission object. It is used to transmit data between the client and Dao. It is actually a JavaBean.
6. After completing the above five steps, we can use the classes defined above by the DAO design mode on the Data Client (see the last code sample block ).
In the above six steps, you need to have a specific experience in programming. Generally, a table in the database can correspond to a data transmission class, that is, the class defined in step 1, the attribute in the class is the field in the table, and then add the corresponding get and set methods. then define the specific class according to the mode and the above steps.
Translated from: [url] URLs