Java Data Access Objects (DAO) programming mode entry

J2EE developers use the Data Access Object (DAO) design pattern and data access logic level of the underlying business logic separated. DAO implementation mode can focus more on writing data access code in this article, Java developer Sean C. Sullivan from three aspects discussed structural features of DAO programming: transaction demarcation, exception handling, logging.
in the last 18 months, I and a good software development team to work together, to develop custom WEB-based supply chain management applications to us. applications to access a wide range of data persistence layer, including shipping status, supply chain systems, inventory, shipment, project management data, and user attributes. we use the JDBC API to connect to our company's various database platforms, and throughout the application application of DAO design pattern.
by the entire application in the application data access object (DAO) design pattern allows us to access the data underlying logic and business logic separate from the upper. we have created for each data source to provide CRUD (create , read, update, delete) DAO class operation.
in this article, I will introduce you to the DAO implementation strategies and create more DAO classes of technology. I will introduce clear logging, exception handling, and three technical affairs division. You will learn in your DAO classes how combining these three technologies. This article assumes that you are familiar with JDBC API, SQL and relational database programming.
let's take a look at the DAO design pattern and data access objects.
DAO basis
DAO mode is one of the standard J2EE design patterns. developers use this mode data access operation and the upper underlying business a typical logic separate DAO several components to achieve the following:
1. a DAO factory class;
2. a DAO interface;
3. DAO interface implement a concrete class;
4. data transfer objects (sometimes called the target value).
Concrete DAO class contains logic for accessing data from a particular data source below this you will learn to design and implement technical data access objects.
Transaction demarcation:
on one important thing to remember is that they DAO It is a transactional object. each operation is performed DAO (like create, update, or delete data) and the transaction is associated. Similarly, the concept of transaction demarcation (transaction demarcation) is particularly important.
transaction demarcation is in transaction definition defining the divided manner .J2EE transaction specification describes two modes: programmatic transaction (Programmatic) and declarative transaction (declarative) the table is split these two modes:
a declarative programming of transaction demarcation transaction demarcation
programmer using EJB deployment descriptor of transaction attributes declared write transaction logic programmers take responsibility code.
runtime environment (EJB containers) using these attributes to automatically manage the transaction application program to control transaction through an API interface.
I will focus on the programmatic transaction demarcation.
like the previous description, like, DAOs are some of the transaction object. a typical DAO to perform as create, update And delete the transactional operations in designing a DAO, the first question to ask yourself the following questions:
? 1, the transaction will be how to start
? 2, the transaction will be what end
? 3, that object will assume the start of a transaction liability
4, the objects will assume responsibility for the end of a transaction?
5, DAO should take responsibility start and end of the transaction?
6, the application needs to access multiple cross DAO do?
7, a transaction contains one or more DAO DAO?
8, containing a DAO other DAO in the way?
Answering these questions will help you choose the best policy for transaction demarcation DAO object has two main strategies for transaction demarcation in ADO method is to use DAO to assume the responsibility of transaction demarcation;.. The other is an extension of affairs, it is the transaction demarcation to the method call DAO object. If you choose the former, you will want to embed transaction code in DAO classes. If you choose the latter, the transaction code will be written on the outside of DAO class. we will use the simple . the code examples to better understand how these two methods work
example 1 shows a DAO with two data operations: create (create) and update (update):
public void createWarehouseProfile (WHProfile Profile);
public updateWarehouseStatus void (WHIdentifier ID, the StatusInfo Status);
. example 2 demonstrates a simple transaction, a transaction code division outside the DAO classes Note: in this example, the caller of the plurality of operations into the DOA transaction.
TX .begin (); // Start The Transaction
dao.createWarehouseProfile (Profile);
dao.updateWarehouseStatus (ID1, in the STATUS1);
dao.updateWarehouseStatus (ID2, the status2);
tx.co mmit (); // end the transaction
This transaction transaction demarcation strategy is especially important for applications that access multiple DAO in a single transaction for.
You can use the JDBC API can also use the Java Transaction API (JTA) to achieve the division of .JDBC transaction demarcation is simpler than JTA transaction transaction demarcation, but JTA provides greater flexibility. In the following period, we will further . see transaction demarcation mechanism
using JDBC transaction demarcation
JDBC transaction is controlled using the connection object .JDBC connection interface (the java.sql.Connection) provides two transaction modes: automatic and manual submission submission .Java.sql.Connection the following methods for the control of affairs:
.public void setAutoCommit (Boolean)
.public getAutoCommit Boolean ()
.public void the commit ()
.public void ROLLBACK ()
example 3 shows how to demarcate transactions using the JDBC API:
Import java.sql *. ;
Import the javax.sql *;.
// ...
the DataSource ds = obtainDataSource ();
Connection conn = ds.getConnection ();
conn.setAutoCommit (false);
// ...
pstmt = conn.prepareStatement ( "; UPDATE MOVIES ... ";);
pstmt.setString (1, "; at The Great Escape";);
pstmt.executeUpdate ();
// ...
conn.commit ();
// ...
using JDBC transaction demarcation, you can put multiple SQL statements one of the drawbacks to a single transaction .JDBC transaction is a transaction scope is limited to a single database connection. a JDBC transaction can not span multiple databases. Next, we will see how to use the JTA transaction demarcation to do because JTA is not as JDBC as widely understood, so I first summarize what JTA.
JTA provides an overview of
the Java transaction API (JTA; Java transaction API) and its compatriots Java transaction service (JTS; Java transaction service), as J2EE platform provides distributed transaction service. a distributed transaction (distributed transaction) includes a transaction manager (transaction manager) and one or more resource managers (resource manager). a resource manager (resource manager) of any type the persistent data storage. transaction Manager (transaction manager) bear responsibility for all matters of mutual communication unit's participation at the station shows the relationship between the transaction manager and resource management .
JTA transaction is more powerful than JDBC transactions a JTA transaction can have multiple participants, and a JDBC transactions were limited to a single database connection in any of the following components of a Java platform can participate in a JTA transaction..:
. JDBC connection
.JDO PersistenceManager objects
.JMS queue
.JMS theme
. Enterprise JavaBeans (the EJB)
. J2EE Connector Architecture specification with a compiled resource allocator.
Use JTA transaction demarcation
to use JTA to divide a transaction, the application method javax.transaction.UserTransaction interface calls. Example 4 UseTransaction shows a typical JNDI search of the object.
Import the javax.transaction *;.
Import javax.naming *;.
// ...
the InitialContext ctx = new new the InitialContext ();
Object txObj ctx.lookup = ( "; the Java: CoMP / UserTransaction ";);
UserTransaction UTX = (UserTransaction) txObj;
after the application has UserTransaction object reference, can be started as example 5 as a transaction.
utx.begin ();
// ...
the DataSource obtainXADataSource DS = ( );
Connection ds.getConnection Conn = ();
pstmt = conn.prepareStatement ( "; the UPDATE MOVIES ...";);
pstmt.setString (1, "; Spinal the Tap";);
pstmt.executeUpdate ();
// ...
utx.commit ();
// ...
When the application calls the commit (), the transaction manager to use two segment commit protocol to end the transaction .JTA transaction control method:
.javax.transaction.UserTransaction interface provides the following transaction control methods:
.public void the begin ()
.public void the commit ()
.public void ROLLBACK ()
.public void getStatus ( )
.public void the setRollbackOnly ()
.public void setTransactionTimeout (int)
application calls begin () to start the transaction, you can call commit () can also call rollback () to end the transaction.
use JTA and JDBC
Developers often use JDBC to operate as the underlying data DAO class. If you plan to demarcate transactions using JTA, you will need a realization javax.sql.XADataSource, javax.sql.XAConnection and javax.sql.XAResource interfaces JDBC drivers . implement these driver interface will be able to participate in JTA transactions. XAConnection a XADataSource object is an object factory .XAConnections is involved in the connection JTA transaction.
you need to use an application server management tools to create XADataSource objects. for special instructions please refer to the application server documentation and the JDBC driver documentation.
the J2EE applications use JNDI to find the data source. Once the application has a reference to a data source object, it will call javax.sql.DataSource.getConnection () to get connection to the database.
XA connection different from a non-XA connection to remember is that the connection is a JTA XA transaction participants. This means that the JDBC XA connections do not support auto-commit feature. that application does not in XA call java.sql.Connection.commit () or java.sql.Connection.rollback () on the connection. Instead, the application The use UserTransaction.begin (), UserTransaction.commit () and UserTransaction.rollback ().
Select the best method
we have discussed is how to divide JDBC and JTA transactions. Each method has its advantages, this back you need to decide selection method best suited for your application in our team a lot recently for transaction demarcation project using the JDBC API to create DAO classes that DAO classes are summarized as follows:..
. transaction demarcation code is embedded to the DAO class internal
.DAO class uses the JDBC API for transaction demarcation
method caller does not divide the transaction
The transaction scope is limited to a single connection in JDBC
JDBC transactions for complex enterprise applications are not always effective. If your transactions will span multiple a DAO object or multiple databases, then the following implementation strategy may be more appropriate:
for the transaction to be divided with JTA
transaction demarcation code is separated from DAO.
the caller bear responsibility for affairs division.
.DAO participate in a global transaction
JDBC methods Because of its simplicity and attractive, JTA method provides more flexibility. you choose what kind of implementation will depend on the specific needs of your application.
logging and DAO
a good DAO implementation class will use logging to capture details about its run-time behavior. you can choose to log exceptions, configuration information, connection status, JDBC driver metadata or query parameters. logs for the entire development stage are beneficial. I always check application development during logging during testing and the product.
in this, we will show how some combination of the Jakarta Commaons logging An example of a DAO Before we begin, let's review some basics.
Select a log example library
Many developers use a basic form of logs are:. System.out.println statements and this System.err.println.Println . forms fast and convenient, but they do not provide a complete log system capabilities the following table lists the Java platform libraries log:
log library open it the URL of?
the java.util.logging No
Jakarta Log4j is
Jakarta Commons Logging is HTTP: /Jakarta.apache.org/commons/logging.html
the java.util.logging is the standard platform API on J2SE1.4 However, most developers agree that Jakarta Log4j provides more. great functionality and flexibility .Log4j beyond java.util.logging one of the advantages is that it supports J2SE1.3 and J2SE1.4 platform.
Jakarta Commons Logging can be used and java.util.loggin or Jakarta Log4j work together. Commons logging is your application independent abstraction layer logging implementations. Commons logging you use to exchange data can be implemented with the following log by changing a profile is used JAKARTA Struts1.1 .Commons logging and Jakarta HttpClient2. 0 in
an exemplary log
example 7 shows how to use Jakarta Commons logging in a DOA class
Import org.apache.commons.logging *;.
class DocumentDAOImpl the implements DocumentDAO
{
static Private Final LogFactory.getLog the log = log (DocumentDAOImpl.class) ;
public void deleteDocument (String ID)
{
... //
log.debug ( "; Deleting Document:"; + ID);
// ...
the try
{
// ... ... Data Operations
}
the catch (SomeException EX)
{
log.error ( "; the Document to the Delete Unable "; EX);
// ... handle at the Exception ...
}
}
}
. log is an essential part of the evaluation of the application if you encounter a failure in a DAO, the log often to understand what happened error provide the best information. log into your combine the DAO to ensure an effective means of debugging and problem solving to get.
DAO exception handling
we've looked at transaction demarcation and logging, and now for how they are applied to the data have access to the object of an in-depth understanding. exception handling is our third and final part to be discussed. the following are some simple exception handling guidelines to use your DAO easier to use, more robust and more maintainable.
in the realization of DAO mode when you want to test the filter following question:
methods in the public interface of the DAO will throw an exception is checked it?
If so, what kind of inspection will throw an exception.?
how in the DAO implementation class. samples can handle exceptions.
In the process of working with the DAO model, exception handling our team developed a set of guidelines to improve your DAO following these guidelines will have a significant degree of:.
.DAO methods should throw meaningful exception.
.DAO method does not java.lang.Exception should throw an exception because java.lang.Exception is too generic, it can not contain all the information about potential problems.
.DAO method should not throw an exception java.sql.SQLException .SQLException is a low-level JDBC abnormal, DAO application packaging efforts JDBC exceptions should not be left to other parts of the abnormal JDBC application.
the method in DAO interface should throw only expect the caller to check the abnormal treatment. If the caller can not use the appropriate method to handle the exception, not the test filter thrown examination of the (run-time runtime) exception.
If your data access code catches an exception, not to ignore it. ignore DAO capture the exception is processed.
. using exceptions chain to pass the exception of the bottom to the top of a processor
. define a standard test filter DAO exception classes .Spring framework provides an excellent set of DAO predefined exception classes.
See Resources, View more detailed information have exceptions and exception handling techniques.
Implementation Example: MovieDAO
. MoveDAO is a demonstration of all the technology discussed in this article, including transaction demarcation, logging and exception handling you will find in the Resources section MovieDAO it is the source code is divided three packets following:.
.daoexamples.exception
.daoexamples.move
.daoexamples.moviedemo
DAO mode to achieve this by the following classes and interfaces:
.daoexamples.movie.MovieDAOFactory
.daoexamples.movie.MovieDAO
.daoexamples.movie.MovieDAOImpl
.daoexamples.movie.MovieDAOImplJTA
.daoexamples.movie.Movie
.daoexamples.movie.MovieImple
. daoexamples.movie.MovieNotFoundException
.daoexamples.movie.MovieUtil
MovieDAO interface defines the interface to the operating data DAO has the following five methods:.
.public Movie findMovieById (String ID)
.public java.util.Collection findMoviesByYear (String year)
.public deleteMovie void (String the above mentioned id)
.public Movie CreateMovie (Rating String, String year, String title)
.public void updateMovie (the above mentioned id String, String Rating, String year, String title)
daoexamples.movie MovieDAO package contains two interfaces implemented for each implementation uses a method of dividing the same transaction, the following table:.
MovieDAOImpl MovieDAOImplJTA
implements the interface yet MovieDAO Yes Yes?
obtained via JNDI DataSource it Yes Yes?
from a DataSource java.sql.Connection objects get it? Yes Yes
DAO defining internal affairs of it? Yes No
use JDBC transactions it? Yes No
use a XA DataSource it? No Yes
sharing JTA transaction it? No Yes
MovieDAO demonstration application
this demonstration application program is called daoexamples.moviedemo.DemoServlet.DemoServlet servlet class, it uses Movie DAO to query and update a data table in the movie.
the servlet demonstrates the JTA-aware Java message service MovieDAO and combined into a single transaction as shown in example 8:
the UserTransaction = UTX MovieUtil.getUserTransaction ();
utx.begin ();
Batman = dao.createMovie ( "; R & lt";
"; 2008";
"; Batman Reloaded";);
= new new MessagePublisher Publisher ();
publisher.publishTextMessage ( "; Irll BE Back";);
dao.updateMovie (topgun.getId (),
"; the PG-13 is";
topgun.getReleaseYear (),
topgun.getTitle ());
dao.deleteMovie (legallyblonde.getId ());
utx.commit ();
. to run the sample application, configure a data source and a non-XA XA data source in your application server and then deploy daoexamples.ear file this application will run on any J2EE-compliant application server.

Reproduced in: https: //www.cnblogs.com/521taobao/archive/2012/03/17/2402449.html

Guess you like

Origin blog.csdn.net/weixin_34384681/article/details/93355429