Typical Implementation of DAO Mode - ADVANCED DAO Programming

zhaozj2021-02-16  130

Learn Techniques for building better daos

Level: Advanced

Sean C. Sullivan

(Mailto: DAO-Aticle@seansullivan.com? cc = & subject = advanced Dao programming) Software Engineer7 October 2003

J2EE developers use the Data Access Object (DAO) design pattern to separate low-level data access logic from high-level business logic. Implementing the DAO pattern involves more than just writing data access code. In this article, Java developer Sean C. Sullivan Discusses Three OfferLooked Aspects of Dao Programming: Transaction Demarcation, Exception Handling, and Logging.

During the past 18 months I worked with a team of talented software engineers to build custom Web-based supply chain management applications. Our applications accessed a broad range of persistent data, including shipment status, supply chain metrics, warehouse inventory, carrier invoices, project Management Data, And User Profiles. We buy Our Company's Various Database Platforms and Applied The Dao Design Pattern Throughout The Applications.

Figure 1 Shows The RELATION BETWEEN The Applications and Data Sources:

Figure 1. Applications and Data Source

Applying the Data Access Object (DAO) pattern throughout the applications enabled us to separate low-level data access logic from business logic. We built DAO classes that provide CRUD (create, read, update, delete) operations for each data source.

In this article, I'll introduce you to DAO implementation strategies and techniques for building better DAO classes. Specifically, I'll cover logging, exception handling, and transaction demarcation. You will learn how to incorporate all three in your DAO classes. This Article Assumes That You Are Familiar with the JDBASE Programming.We'll Start With A Review of The Dao Design Pattern and Data Access Objects.

.. DAO fundamentalsThe DAO pattern is one of the standard J2EE design patterns Developers use this pattern to separate low-level data access operations from high-level business logic A typical DAO implementation has the following components:

A DAO Factory Class A DAO Interface A Concrete Class That Implements The Dao Interface Data Transfer Objects (Sometimes Called Value Objects)

The concrete DAO class contains logic for accessing data from a specific data source. In the sections that follow you'll learn techniques for designing and implementing data access objects. See Resources to learn more about the DAO design pattern.

Transaction demarcationThe important thing to remember about DAOs is that they are transactional objects Each operation performed by a DAO -. Such as creating, updating, or deleting data -. Is associated with a transaction As such, the concept of transaction demarcation is extremely IMPORTANT.

Transaction demarcation is the manner in which transaction boundaries are defined The J2EE specification describes two models for transaction demarcation:.. Programmatic and declarative Table 1 breaks down the two models:

Table 1. Two Models of Transaction Demarcation

Declarative transaction demarcationProgrammatic transaction demarcationThe programmer declares transaction attributes using an EJB deployment descriptor.The programmer is responsible for coding transaction logic.The run-time environment (the EJB container) uses the attributes to automatically manage transactions.The application controls the transaction via an API .We'll focus on programmatic Transaction Demarcation.

Design considerationsAs stated previously, DAOs are transactional objects A typical DAO performs transactional operations such as create, update, and delete When designing a DAO, start by asking yourself the following questions..:

How will transactions start? How will transactions end? Which object will be responsible for starting a transaction? Which object will be responsible for ending a transaction? Should the DAO be responsible for starting and ending transactions? Will the application need to access data across multiple DAOS? WILL A TRANSAOS? WILL A DAO INVOKE METHODS ON ANOTHER DAO?

Knowing the answers to these questions will help you choose the transaction demarcation strategy that is best for your DAOs There are two main strategies for transaction demarcation in DAOs One approach makes the DAO responsible for demarcating transactions;.. The other defers transaction demarcation to the object that is calling the DAO's methods. If you choose the former approach, you will embed transaction code inside the DAO class. If you choose the latter approach, transaction demarcation code will be external to the DAO class. We'll use simple code examples to Better Understand How Each of these approaches works.

Listing 1 Shows A Dao with Two Data Operations: Create and Update: Listing 1. Dao Methods

Public Void CreateWarehouseProfile (Whprofile profile);

Public void UpdateWarehouseStatus (Whidentifier ID, STATUSINFO STATUS);

Listing 2 Shows A Simpe Transaction. The Transaction DEO CODE IS External To The Dao Class. Notice How The Caller In this Example Combines Multiple Dao Operations Wtem.

Listing 2. Caller-managed transaction

TX.BEGIN (); // Start the Transaction

Dao.createWarehouseProfile (profile);

Dao.updateWarehouseStatus (ID1, status1);

DAO.UPDATEWAREHOUSTATUS (ID2, STATUS2);

Tx.commit (); // end the transaction

That Transaction Demarction Strategy Is Especially Valuable for Applications That Need To Access Multiple DAOS in a Single Transaction.

You can implement transaction demarcation using either the JDBC API or the Java Transaction API (JTA). JDBC transaction demarcation is simpler than JTA transaction demarcation, but JTA provides greater flexibility. In the sections that follow we'll take a closer look at the mechanics Of Transaction Demarcation.

Transaction demarcation with JDBCJDBC transactions are controlled using the Connection object The JDBC Connection interface (java.sql.Connection) provides two transaction modes:.. Auto-commit and manual commit The java.sql.Connection offers the following methods for controlling transactions:

Public void setAutocommit (boolean) public boolean getautocommit () public void commit () public void rollback ()

Listing 3 Shows How To Demarcate a Transaction Using The JDBC API:

Listing 3. Transaction Demarcation with the JDBC API

Import java.sql. *;

Import javax.sql. *;

// ...

DataSource DS = ObtainDataSource ();

Connection conn = ds.getConnection (); conn.setautocommit (FALSE);

// ...

PSTMT = conn.preparestatement ("Update Movies ...");

PSTMT.SetString (1, "The Great Escape");

PSTMT.ExecuteUpdate ();

// ...

CONN.COMMIT ();

// ...

With JDBC transaction demarcation, you can combine multiple SQL statements into a single transaction. One of the drawbacks of JDBC transactions is that the transaction's scope is limited to a single database connection. A JDBC transaction can not span multiple databases. Next, we'll see How Transaction Demarcation IS Done Using JTA. Because JTA IS NOT AS WIDELY KNOWN AS JDBC, We'll Start with an offView.

Overview of JTAThe Java Transaction API (JTA) and its sibling, the Java Transaction Service (JTS), provide distributed transaction services for the J2EE platform. A distributed transaction involves a transaction manager and one or more resource managers. A resource manager is any kind The Transaction Manager Is Responsible for Coordinating Communication Between All Transaction Participants. The Relationship Between The Transaction Manager and Resource Managers Is Shown in Figure 2:

Figure 2. a Transaction Manager and Resource Managers

JTA transactions are more powerful than JDBC transactions While a JDBC transaction is limited to a single database connection, a JTA transaction can have multiple participants Any one of the following Java platform components can participate in a JTA transaction..:

JDBC Connections JDO PersistenceManager Objects JMS Queues JMS Topics Enterprise JavaBeans A Resource Adapter That Complies with the J2EE Connector Architecture Specification

Transaction demarcation with JTATo demarcate a transaction with JTA, the application invokes methods on the javax.transaction.UserTransaction interface Listing 4 shows a typical JNDI lookup for the UserTransaction object:. Listing 4. A JNDI lookup for the UserTransaction object

Import javax.transaction. *;

Import javax.naming. *;

// ...

InitialContext CTX = New InitialContext ();

Object TXObj = CTX.lookup ("Java: Comp / UsertransAction);

Usertransaction utx = (userTransaction) TXOBJ;

After the application has a reference to the use ofrtransaction Object It May Start The Transaction, AS Shown In Listing 5:

Listing 5. Starting a Transaction with JTA

Utx.begin ();

// ...

DataSource DS = Obtainxadatasource ();

Connection conn = ds.getConnection ();

PSTMT = conn.preparestatement ("Update Movies ...");

PSTMT.SetString (1, "spinal tap");

PSTMT.ExecuteUpdate ();

// ...

Utx.commit ();

// ...

.....................

JTA Methods for Transaction Controlthe Javax.Transaction.usertransaction Interface Provides The Following Transaction Control Methods:

Public void key () public void problem () public void etstatus () PUBLIC VOID SETROLLLBACKONLIC VOID SETTRANSACTIONTIMEOUT (INT)

To Start a Transaction The Application Calls Begin () or rollback (). See Resources To Learn More About Transaction Management with JTA.

Using JTA and JDBCDevelopers often use JDBC for low-level data operations in DAO classes. If you plan to demarcate transactions with JTA, you will need a JDBC driver that implements the javax.sql.XADataSource, javax.sql.XAConnection, and javax. sql.XAResource interfaces. A driver that implements these interfaces will be able to participate in JTA transactions. An XADataSource object is a factory for XAConnection objects. XAConnections are JDBC connections that participate in JTA transactions.You will be required to set up the XADataSource using Your Application Server's Administrative Tools. Consult The Application Server Documentation and The JDBC Driver Documentation for Specific Instructions.

J2EE Applications Look Up The Data Source Using JNDI. Once The Application Has A Reference To The Data Source Object, It Will Call Javax.sql.dataSource.getConnection () To Obtain a connection to the database.

XA connections are different from non-XA connections. Always remember that XA connections are participating in a JTA transaction. This means that XA connections do not support JDBC's auto-commit feature. Also, the application must not invoke java.sql.Connection.commit () or java.sql.connection.rollback () on an Xa connection. Instead, the application shop (), userTransaction.commit (), and useertransaction.rollback ().

Choosing the best approachWe've discussed how to demarcate transactions with both JDBC and JTA. Each approach has its advantages and you will need to decide which one is most appropriate for your application.

ON MANY Recent Projects Our Team Has Built Dao Classes Using The JDBC API for Transaction Demarcation. These Dao Classes Can Be Summarized As Follows:

Transaction demarcation code is embedded inside the DAO class. The DAO class uses the JDBC API for transaction demarcation. The caller has no way to demarcate the transaction. Transaction scope is limited to a single JDBC Connection.JDBC transactions are not always suitable for complex enterprise Applications. If Your Transactions Will SPAN Multiple DAOS or Multiple Databases The Following Implementation Strategy May Be More Appropriate:

Transactions Are Demarcated with JTA. Transaction Demarcation Code Is Sepament from The Dao. The Caller Is Responsible for Demarcating The Transaction. The Dao PartCIPATES IN A Global Transaction.

The JDBC Approach Is Attractive Due To ITS Simplicity; The JTA Approach Offers Greater Flexibility. The Implementation You Choose Will Depend On The Specific Needs of Your Application.

Logging and DAOsA well-implemented DAO class will use logging to capture details about its run-time behavior. You may choose to log exceptions, configuration information, connection status, JDBC driver metadata, or query parameters. Logs are useful in all phases of development . I OFTEN Examine Application Logs During Development, During Testing, and IN Production.

IN this section

Choosing a logging libraryMany developers use a primitive form of logging:.. System.out.println and System.err.println Println statements are quick and convenient but they do not offer the power of a full-featured logging system Table 2 lists logging libraries For the Java Platform:

Table 2. Logging Libraries for the Java Platform

Logging libraryOpen source URLjava.util.loggingNohttp:? //Java.sun.com/j2se/Jakarta Log4jYeshttp: //jakarta.apache.org/log4j/Jakarta Commons LoggingYeshttp: //jakarta.apache.org/commons/logging.htmljava .util.logging is the standard API for the J2SE 1.4 platform. Most developers would agree, however, that Jakarta Log4j delivers greater functionality and more flexibility. One of the advantages of Log4j over java.util.logging is that it supports both the J2SE 1.3 and J2se 1.4 Platforms.

Jakarta Commons Logging can be used in conjunction with java.util.logging or Jakarta Log4j. Commons Logging is a logging abstraction layer that isolates your application from the underlying logging implementation. With Commons Logging, you can swap the underlying logging implementation by changing a configuration File. Commons logging is buy in jakarta struts 1.1 and jakarta httpclient 2.0.

A logging ExampleListing 7 Shows How To Use Jakarta Commons Logging in a Dao Class:

Listing 7. Jakarta Commons Logging in a Dao Class

Import org.apache.commons.logging. *;

Class DocumentDaoImpl Implements Documentdao

{

Static Private Final Log Log = logfactory.getlog (DocumentDaoImpl.class);

Public void deletedocument (String ID)

{

// ...

Log.debug ("DELETING Document:" ID);

// ...

Try

{

// ... Data Operations ...

}

Catch (Someexception EX)

{

LOG.Error ("Unable to delete Document", EX);

// ... Handle The Exception ...

}

}

}

Logging is an essential part of any mission-critical application. If you encounter a failure in a DAO, logs often provide the best information for understanding what went wrong. Incorporating logging into your DAOs ensures you will be equipped for debugging and troubleshooting.

Exception handling in DAOsWe've looked at transaction demarcation and logging and you now have a deeper understanding of how each applies to data access objects. Our third and final discussion point is exception handling. Following a few simple exception handling guidelines will make your DAOs easier To use, more robust, and more maintainable.when importing the lotion qustions:

WILL METHODS IN THE DAO'S PUBLIC Interface Throw Checked Exceptions? If Yes, What Checked Exceptions Will BE Thrown? How Will Excetions Be Handled WITHIN THE DAO Implementation Class?

In The Process of Working with the Dao Pattern, Our Team Developed A Set of Guidelines for Exception Handling. Follow There Guidelines To Great Improve Your DAOS:

DAO methods should throw meaningful exceptions. DAO methods should not throw java.lang.Exception. A java.lang.Exception is too generic. It does not convey any information about the underlying problem. DAO methods should not throw java.sql.SQLException. SQLException is a low-level JDBC exception. A DAO should strive to encapsulate JDBC rather than expose JDBC to the rest of the application. Methods in the DAO interface should throw checked exceptions only if the caller can reasonably be expected to handle the exception. If the caller will not be able to handle the exception in a meaningful way, consider throwing an unchecked (run-time) exception. If your data access code catches an exception, do not ignore it. DAOs that ignore caught exceptions are difficult to troubleshoot . Use chained exceptions to translate low-level exceptions into high-level ones. Consider defining standard DAO exception classes. The Spring Framework (see Resources) provides an excellent set of predefined DAO exceptio N classes.see resources for more detailed information about exceptions and exception handling techniques.

Implementation example: MovieDAOMovieDAO is a DAO that demonstrates all of the techniques discussed in this article: transaction demarcation, logging, and exception handling You will find the MovieDAO source in the Resources section The code is divided into three packages..:

DaoExamples.Exception Daoexamples.Movie daoexamples.moviedemo

This Implementation of the Dao Pattern Consists of the classs and interfaces shown Below:

daoexamples.movie.MovieDAOFactory daoexamples.movie.MovieDAO daoexamples.movie.MovieDAOImpl daoexamples.movie.MovieDAOImplJTA daoexamples.movie.Movie daoexamples.movie.MovieImpl daoexamples.movie.MovieNotFoundException daoexamples.movie.MovieUtilThe MovieDAO interface defines the DAO's data operations. The interface Has Five Methods, As Shown Here:

public Movie findMovieById (String id) public java.util.Collection findMoviesByYear (String year) public void deleteMovie (String id) public Movie createMovie (String rating, String year, String, title) public void updateMovie (String id, String rating, String Year, string title)

The daoExamples.movie package contaIn interface. Each Implementation Uses a Different Approach To Transaction Demarcation, AS Shown In Table 3: AS SHOWN TABLE 3:

Table 3. Moviedao Implementations

MovieDAOImplMovieDAOImplJTAImplements the MovieDAO interface? DataSource via YesYesObtains JNDI? YesYesObtains java.sql.Connection objects from a DataSource? YesYesDAO demarcates transactions internally? YesNoUses JDBC transactions? YesNoUses an XA DataSource? NoYesParticipates in JTA transactions? NoYes

Moviedao Demo ApplicationThe Demo Application IS A Servlet Class Called DaoExamples.Moviedemo.deMoservlet. Demoservlet Uses Both of The Movie Daos To Query and Update Movie Data IN A TABLE.

THE Servlet Demonstrates How To Combine The JTA-Aware Moviedao and The Java Message Service IN A Single Transaction, AS Shown In Listing 8.

Listing 8. Combining Moviedao and JMS Code in a Single Transaction

UserTransaction utx = movieutil.getusertransaction ();

Utx.begin ();

Batman = dao.createmovie ("r",

"2008",

"Batman Reloaded");

Publisher = new messagepublisher (); publisher.publishtextMessage ("i'll be back");

Dao.updatemovie (TopGun.GetId (),

"PG-13",

Topgun.getReleaseYear (),

TopGun.gettitle ());

Dao.deletemovie (legallyblonde.getid ());

Utx.commit ();

To run the demo application, configure an XA datasource and a non-XA datasource in your application server. Then, deploy the daoexamples.ear file. The application will run in any J2EE 1.3-compliant application server. See Resources to obtain the EAR file And Source Code.

ConclusionAs this article has shown, implementing the DAO pattern entails more than just writing low-level data access code. You can start building better DAOs today by choosing a transaction demarcation strategy that is appropriate for your application, by incorporating logging in your DAO classes, And by Following a Few Simple Guidelines for Exception Handling.

Resources

Download the MovieDAO source code at daoexamples.sourceforge.net Want to learn more about the Data Access Object pattern? Start with the Core J2EE Patterns home page. Kyle Brown's "A stepped approach to J2EE testing with SDAO" (developerWorks, March 2003) provides a short introduction to data access objects and the DAO design pattern. The Dragonslayer tutorial "Create persistent application data with Java Data Objects" (developerWorks, July 2003) shows you how to combine Struts and the DAO pattern for low-impact enterprise data persistence. Srikanth Shenoy's "Best practices in EJB exception handling" (developerWorks, May 2002) introduces both exception handling basics and logging with Log4j The Java theory and practice series offers a three-part introduction to the Java Transaction API, starting with "Understanding JTS. - - An Introduction to Transactions (DeveloperWorks, March 2002). The Java Transaction API Is a KEY Part of The J2EE Platform. Jakarta log4j is a world-class logging li brary for Java applications. Jakarta Commons Logging provides an easy-to-use logging abstraction layer. The Spring Framework provides abstraction layers for JDBC and transaction management. Additionally, the framework contains standardized DAO exception classes and JNDI helper classes. Rod Johnson's J2EE Design and Development (Wrox Press, 2002) Belongs On Every J2ee Developer's Bookshelf. The Book is Full of Application Design Strategies, Practical Programming Techniques, and real-world example. Josh Bloch '

s Effective Java Programming Language Guide (Addison Wesley, 2001) presents best practices for exception handling and class library design. See the Java technology zone tutorials page for a complete listing of free Java technology tutorials from developerWorks. You'll find hundreds of articles about every aspect of Java programming in the developerWorks Java technology zone.About the authorSean C. Sullivan is a software engineer working in Portland, Oregon. His most recent projects include building supply chain management applications and an Internet e-commerce payment system. He has also worked on operating system and CAD software projects at IBM and Image Systems Technology. Sean is an Apache Jakarta developer, having contributed code to the Jakarta HttpClient project. He has been developing applications with Java since 1996 and is the author of Programming with the Java Media Framework, Published by John Wiley & Sons. Sean Holds A BS in Computer Science from rensselar. He Can Be Re Ached at dao-Article@seansullivan.com.

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

New Post(0)