Read "J2EE Core Mode" (DAO mode)

xiaoxiao2021-03-06  65

Many J2EE applications require persistence data (database, file, etc.). Different procedures, persistence storage is different, and the APIs use to access these different persistence storage mechanisms are also very different. If the application is migrating between different persistence memory, these access to a specific persistent storage layer will face overwriting.

How to solve this problem? And see "DAO mode"

Data Access Object (Data Accom Object) mode

I. The environment is different depending on the data source, and the data access is different. Depending on the type of storage (relational database, object-oriented database, file, etc.) and vendor implementation, persistent storage (such as database) has great differences.

II. Many true J2EE applications need to use persistent data to some extent. For many applications, persistent storage is implemented using different mechanisms, and uses APIs accessing these different persistence storage mechanisms. For example, the application uses entity beans (here, BMP's bean, CMP BEAN has greatly reduced distributed components with RDBMS) to represent persistence data, or use JDBC API to access resident in a relationship database Data in the Manage System (RDBMS), which contains connectivity and data access code in the components, which are incorporated between these components and data source implementations. Such code dependence in the component will make the application migrate from some kind of data source to other kinds of data sources will become very troublesome and difficult. When the data source changes, the components also need to be changed to facilitate processing new types of data sources.

(For example, our Uptel system is to connect and data access to the Oracle database using the JDBC API. These JDBC APIs are spread in the system. When we need to migrate Uptel to other RDBMs, such as once migrated to Informix, it faces a module that rewrites database connections and access data.)

III. Structure 1. Entity Bean, Session Bean, Servlet, such as bean, tend to retrieve data from persistent storage data sources, and data storage. 2. Depending on the product supplier, the durable storage API is also very different. These APIs and their capabilities are also different depending on the type of storage, so that the following shortcomings are not uniform. 3. Components need to be transparent to actual persistence storage or data source implementation to facilitate easier portability of different supplier products, different storage types, and different data source types.

4. Solution Use the Data Access Object (DAO) mode to abstract and encapsulate all access to the data source. DAO manages the connection to the data source to retrieve and store data. DAO implements access mechanisms for operating the data source. The data source can be RDBMS, LDAP, FILE, etc. Business components depend on DAO provide simpler interfaces for their clients using DAO. DAO completely hides the data source implementation details to the client. Since when the low-level data source is changed, the interface provided to the client will not change, all of which allows DAO to adjust to different storage modes without affecting its clients or business components. Importantly, DAO acts as an adapter between components and data sources.

(According to this theory, if the Uptel system uses the DAO mode, you can migrate from Oracle to any RDBMS from Oracle. Dream is always perfect, and see how DAO mode is implemented)

1. Structure, Fig. 1 is a class diagram showing various relationships in the DAO mode.

The related pictures of this topic are as follows:

2. Participants and Responsibilities 1) BusinessObject (Business Object) represents the data client. It is this object that needs to access the data source for acquisition and storage data. 2) DataAccessObject (Data Access Object) is the main object of this mode. DataAccessObject extracts the low-level data access implementation of the businessObject to ensure transparent access to the data source. BusinessObject can also delegate data loading and storage operations to DataAccessObject. 3) DataSource represents the data source. The data source can be each RDBMSR database, OODBMS, XML file, and more. 4) ValueObject (value object) represents the value object carrying the data. DataAccessObject can use value objects to return data to the client. DataAccessObject may accept data from the client, where these data for updating the data source is stored in the value object. 3. Strategy 1). Automatic DAO code generating strategy Because each BusinessObject corresponds to a special DAO, it is possible to establish a relationship between businessObject, DAO, and low-layer implementation (such as RDBMS) (mapping). One point (mapping) has been established, we can write simple tools generated with the code of the application's pavilion (what? Write your GP program? Automatically generate it with ORM's entry, write a few Adapter yourself. , The cattle is different, you have to write ...), where the tool can generate all DAO code required for the application. If DAO demand is complicated, we can use third-party tools, which provide objects to the RDBMS database (here, the ORM tool mentioned earlier, "full name is OBJECT RELATION MAPPING, there are many mature ORM tools: Hibernate, Ojb, Torque, Toplink, etc.). These tools typically include a GUI tool to map business objects to persistent storage objects, and thus define intermediate DAOs. Once these mappings are completed, these tools automatically generate code, and may provide other value-added functions, such as results buffer, query buffer, integration with applications, and other third-party products (such as distributed buffering), etc. . (Value-added services: Torque provides results buffer, Hibernate provides optimization for Oracle database SQL instructions, OJB provides JDO API, OMDB API)

2). Factory strategy for data access objects By adjusting abstract factories and factory method patterns, DAO models can achieve high flexibility. When the low-layer storage does not change as the implementation changes, the policy can use the factory method mode to implement the policy. A large number of DAOs needed to generate applications. Figure 2 is a class diagram in this case.

The related pictures of this topic are as follows:

When the low-layer storage changes with the change, the policy can be implemented using an abstract factory method mode. Figure 3 is a class diagram in this case.

The related pictures of this topic are as follows:

5. Results 1). Enable transparency business objects can be used in use without understanding the specific details of the data source implementation. Access is transparent because it is implemented inside the DAO. 2). Enabling easier migration DAO layers make applications easier to migrate to a different database implementation. Business objects do not understand low-level data implementation. Thus, the migration involves only changes in the DAO layer. Furthermore, if you use a factory strategy, it is possible to provide a specific factory implementation for each low-level storage implementation. In this case, migration to a different migration implementation means providing a new factory implementation to the application. 3). Reduce the code complexity in business objects Due to DAO management of all data access complexity, it can simplify the business object and other code in the client using DAO. All code related to implementation (such as SQL statements) are included in DAO, not included in business objects. This improves the readability of the code and has been code productivity. 4) Top all data access to a separate layer. Because all data access operations are now delegated to DAO, all individual data access layers can be seen as part of the data access to other code in the application. This centralization makes the application more easily and manages. 5). Not applicable to container management persistence due to the persistence (CMP) of EJB container management, the container automatically serves all persistent storage access. The application of entity beans managed by the container does not require a DAO layer because the application server is transparently providing this feature. However, when using CMP and BMP, when needed to use CMP and BMP, DAO is still useful. 6). Adding Other Layers DAO Create other object layers between the data client and the data source, where the data source needs to be designed and implemented to weigh the benefits of this mode. But select this method also brings additional overhead. 7). Requires class level design In the use of factory strategies, we need to design and implement the level of specific factories, and the specific product levels produced by these plants. If you can ensure this flexibility, it is necessary to consider this additional work. This will increase the complexity of the design. However, when implementing the factory strategy, you can first consider the factory method mode, then transition to the abstract factory as needed. 6. Sample Code 1. Implement Data Access Object Mode 9-4 indicates the DAO sample code of the persistent object of Customer information. When FindCustomer () is called, CloudscapeCustomerDao creates a Customer value object. Example 9-6 is an example code using DAO.

2. Factory Policy for Data Access Object 1) Using Factory Method 2) Using Abstract Factory Model Code 9-2 is an example code of CloudscapeDaOfactory. The CustomerDao interface in Sample Code 9-3 defines a DAO method for the Customer persistence object, which is implemented by all specific DAO, such as CloudscapeCustomerdao, Oraclectomerdao, SybaseCustomerdao. Accent and OradDao interfaces are similar to this.

Example 9.1 Abstract Daofactory Class

// Abstract Class Dao FactoryPublic Abstract Class Daofactory {

// list of dao types supported by the factorypublic 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 to // implement these methods.public abstract CustomerDAO getCustomerDAO ();. Public abstract AccountDAO getAccountDAO (); public abstract OrderDAO getOrderDAO (); ... 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;}}}

Example 9.2 Concrete Daofactory Implementation for Cloudscape

// Cloudscape Concrete Dao Factory ImplementationImport 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 connectionspublic static Connection createConnection () {// Use DRIVER and DBURL to create a connection // Recommend connection pool implementation / usage} public CustomerDAO getCustomerDAO () {// CloudscapeCustomerDAO implements CustomerDAOreturn new CloudscapeCustomerDAO ();} public AccountDAO getAccountDAO () {// CloudscapeAccountDAO implements AccountDAOreturn new CloudscapeAccountDAO ();} public OrderDAO getOrderDAO () {// CloudscapeOrderDAO implements OrderDAOreturn new CloudscapeOrderDAO ();} ...}

Example 9.3 Base Dao Interface for Customer

// Interface that all CustomerDAOs must supportpublic interface CustomerDAO {public int insertCustomer (...); public boolean deleteCustomer (...); public Customer findCustomer (...); public boolean updateCustomer (...); public RowSet selectCustomersRS (...); public collection selectcustomersvo (...); ...

Example 9.4 Cloudscape DAO Implementation for Customer // CloudscapeCustomerDAO implementation of the // CustomerDAO interface. This class can contain all // Cloudscape specific code and SQL statements. // The client is thus shielded from knowing // these implementation details.

Import java.sql. *;

Public class cloudscapecustomerdao imports Customerdao {public cloudscapecapecustomerdao () {// initialization}

// t following methods can use // cloudscapedaofactory.createConnection () // TO GET A connection as request

Public int insertcustomer (...) {// Implement INSERT Customer Here.// Return Newly Created Customer Number // OR A-1 On Error} Public Boolean DeleteCustom (...) {// Implement Delete Customer Here // Return True on success, false on fiveure}

Public Customer FindCustomer (...) {// Implement Find A Customer Here Using Supplied // Argument Values ​​As Search criteria // Return a value object if found, // Return Null on Error or if not found}

Public Boolean UpdateCustomer (...) {// Implement Update Record Here Using Data // from The CustomerData Value Object // Return True on Success, False On Failure OR // Error}

Public Rowset SelectCustomersrsrs (...) {// Implement Search Customers Here Using The // Supplied criteria.// Return a rowset.}

Public Collection SelectCustomersvo (...) {// Implement Search Customers Here Using The // Supplied Criteria.// Alternative, Implement To Return A Collection // of Value Objects.} ...}

EXAMPLE 9.5 Customer Value Object

Public class customer imports java.io.serializable {// member variablesint customernumber; string name; string streetaddress; string city; ...

// getter and setter methods ......}

EXAMPLE 9.6 Using A DAO AND DAO FACTORY? Client Code

... // create the required DAO FactoryDAOFactory cloudscapeFactory = DAOFactory.getDAOFactory (DAOFactory.DAOCLOUDSCAPE); // Create a DAOCustomerDAO custDAO = cloudscapeFactory.getCustomerDAO ();

// Create a new customerint newcustno = custdao.insertcustomer (...);

// Find a Customer Object. Get the value object.customer Cust = CustDao.findCustomer (...);

// modify the values ​​in the value object.cust.setaddress (...); cust.setemail (...); // update the customer object useing the daustdao.updatecustomer (CUST);

// delete a customer objectcustDAO.deleteCustomer (...); // select all customers in the same city Customer criteria = new Customer (); criteria.setCity ( "Canton"); Collection customersList = custDAO.selectCustomersVO (criteria); // Returns Customerslist - Collection of Customer // Value Objects. IteeRrate THIS Collection to // Get Values.

...

转载请注明原文地址:https://www.9cbs.com/read-112233.html

New Post(0)