Learn techniques for building better DAOs
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 used the JDBC API to connect to 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 sources
Top 22 Java Design Patterns Interview Questions & Answers last updated November 10, 2018 / 0 Comments / in Java & Javascript / by renish 1) Explain what is Java Design Pattern? One of them is using IntelliJ to manipulate.fxml file or using SceneBuilder to design the UI. Using SceneBuilder when creating and designing UI at the first time is much easier and reasonable. I generally use intelliJ for manipulating UI at later stages. Into the middle pane of SceneBuilder. DAO In Java Complete JDBC Tutorial Java Model View Controller (MVC) Design Pattern Java Value Object Pattern Data Access object (DAO) Design Pattern Java Architecture Over View Distributed transaction in java Commiting and Rolling Back transaction Turning transaction off and on JDBC Transaction ACID property. DAO means Data Access Object and is an industry design pattern. In this article, I will discuss What is a DAO and how to create a DAO. DAO Design Pattern. DAO stands for Data Access Object. DAO Design Pattern is used to separate the data persistence logic in a separate layer. This way, the service remains completely in dark about how the low-level operations to access the database is done.
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 JDBC API, SQL, and relational database programming.
We'll start with a review of the DAO design pattern and data access objects.
DAO fundamentals
The 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:
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 Related topics to learn more about the DAO design pattern.
Transaction demarcation
The 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
We'll focus on programmatic transaction demarcation.
Design considerations
As 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:
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
Listing 2 shows a simple transaction. The transaction demarcation code is external to the DAO class. Notice how the caller in this example combines multiple DAO operations within the transaction.
Listing 2. Caller-managed transaction
This transaction demarcation 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 JDBC
JDBC 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:
Listing 3 shows how to demarcate a transaction using the JDBC API:
Listing 3. Transaction demarcation with the JDBC API
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 cannot 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 overview.
Overview of JTA
The 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 of persistent datastore. 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:
Transaction demarcation with JTA
To 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
After the application has a reference to the
UserTransaction object it may start the transaction, as shown in Listing 5:
Listing 5. Starting a transaction with JTA
When the application invokes
commit() , the transaction manager uses a two-phase commit protocol to end the transaction. Main azaad hoon movie song free download 2017.
JTA methods for transaction control
The
javax.transaction.UserTransaction interface provides the following transaction control methods:
To start a transaction the application calls
begin() . To end a transaction the applicationcalls either commit() or rollback() . See Related topics to learn more about transaction management with JTA.
Using JTA and JDBC
Developers 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. XAConnection s 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 should use UserTransaction.begin() , UserTransaction.commit() , and UserTransaction.rollback() .
Choosing the best approach
We'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:
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:
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 DAOs
A 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, I'll present a code example that shows how to incorporate Jakarta Commons Logging into a DAO. Before we get to that, let's review a couple of basics.
Dao Design Pattern In JavaChoosing a logging library
Many 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
java.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 used in Jakarta Struts 1.1 and Jakarta HttpClient 2.0.
A logging example
Listing 7 shows how to use Jakarta Commons Logging in a DAO class:
Listing 7. Jakarta Commons Logging in a DAO class
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 beequipped for debugging and troubleshooting.
Java Dao TutorialException handling in DAOs
We'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 implementing the DAO pattern, consider the following questions:
In the process of working with the DAO pattern, our team developed a set of guidelines for exception handling. Follow these guidelines to greatly improve your DAOs:
Matlab free download with crack. See Related topics 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 Related topics section. The code is divided into three packages:
This implementation of the DAO pattern consists of the classes and interfaces shown below:
The
MovieDAO interface defines the DAO's data operations. The interface has five methods, as shown here:
The
daoexamples.movie package contains two implementations of the MovieDAO interface. Each implementation uses a different approach to transaction demarcation, as shown in Table 3:
Table 3. MovieDAO implementations
MovieDAO demo application
The 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
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 Related topics to obtain the EAR file and source code.
Conclusion
As 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.
Downloadable resourcesRelated topics
CommentsDao Design Pattern In Java Pdf File
Sign in or register to add and subscribe to comments.
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |