Data Access Adapter Strategy


A role of the Adapter strategy is to enable Java or .NET components to transparently access heterogeneous data sources.

Scope

Enterprise applications often require connecting to a diverse set of underlying resources. Common proliferation of data access components across an enterprise application yields poor design. With time, the application expands with additional functionality and new integration points. Without a cohesive Integration tier, application maintenance and troubleshooting becomes quite expensive.

Solution

An Adapter component acts as a single gateway to the underlying resources and represents the core of the Data Access Layer. Depending on the type of systems accessed by the application and the underlying technologies such as Java or .NET, the Adapter component encapsulates corresponding data access functionality. An Adapter is also responsible for transactional context propagation as well as error handling. The example demonstrates how to build simple Adapter components in both Java and .NET. This component hides details of the underlying legacy system and enables access to the heterogeneous back-end environment. Figure 6-4 outlines the Integration Tier that is also referred to as the Data Access Layer:

Figure 6-4. Data Access Layer


Benefits and Limitations

In both Java and .NET applications, this strategy can be applied easily to build a DAL. The main advantage of this strategy is the lack of tight dependencies between the underlying resources and the application logic. From a maintenance standpoint, the Adapter component consolidates logic to access an individual resource, which simplifies maintenance and the troubleshooting process.

One of the important aspects of the DAL is transactional and security support. Transactional boundaries are particularly critical when a single call spans across multiple resources. Being able to restore data to the original state in case of a failure has to be addressed during the design phase. Similarly, access to the individual back-end applications has to be authenticated and authorized. Building a common security mechanism to protect access to the Resource tier also has to be addressed at design time.

Related Patterns

The Data Access Object (DAO) pattern from the Core J2EE Patterns [CJ2EEP] defines an abstraction to encapsulate CRUD operations to the underlying RDBMS. The Adapter strategy can leverage DAO objects to connect to underlying databases. The Adapter strategy goes beyond basic database connectivity, as individual adapters have to connect to legacy systems.

The example that follows demonstrates how to implement an Adapter strategy in Java and .NET.

Example 1: .NET Data Access Adapter

Given that individual steps involved in creating a connection and executing an SQL statement have already been covered, now it is time to simply put it all together and illustrate how to build an Adapter that alternates between two different databases. In this case it is MySql and SQL Server. From the business logic, if the Warehouse_A, represented with MySql, is offline, an Adapter automatically connects to the Warehouse_B, represented with SQL Server.

To execute the .NET Data Access Adapter example, you need to download and place the CoreLab.MySql.dll managed provider for MySql into the corresponding chapter6\lib directory. See [CoreLab] to install the solution.

Listing 6-9 lists the C# code for the connectToMySql() method corresponding to the Warehouse_A, MySql connection for the .NET based Data Access Adapter:

Listing 6-9. C# Method Connecting to Warehouse_A, MySql Server

 public static void connectToMySql(){      Boolean connected = false;      MySqlConnection mySqlConnection = new MySqlConnection();      mySqlConnection.ConnectionString =         "UserId=root;Database=Warehouse_A;Host=localhost;";      string query =        "INSERT INTO ship_goods         VALUES('01JKY977Y','SunFire V40z',2)";      MySqlCommand command = new MySqlCommand(query);      command.Connection = mySqlConnection;      try {        Console.WriteLine("Opening connection");        mySqlConnection.Open();        Console.WriteLine("Connected to the MySql");        connected = true;        Console.WriteLine("Executing query");        int recs = command.ExecuteNonQuery();        if(recs!=0) Console.WriteLine("Query successfully        executed.");          else Console.WriteLine("Query failed.");        Console.WriteLine("Closing MySql connection");        mySqlConnection.Close();      } catch (SqlException e) {        Console.WriteLine(           "Error connecting or communicating with MySql:"           +e.ToString());        connected = false;      } finally{      // Connecting to SqlServer        if (!connected){            Console.WriteLine(               "Couldn't connect to the Warehouse_A,                connecting to Warehouse_B" );        connectToSqlServer();        }      } } 

Similarly, the connectToSqlServer() method connects the Microsoft SQL Server. The C# implementation of this method is listed in Listing 6-10:

Listing 6-10. C# Method Connecting to Warehouse_B, Microsoft SQL Server

 public static void connectToSqlServer(){      string conString =       "DataSource=(local);uid=sa;pwd=admin;database=Warehouse_B";      string query =         "INSERT INTO ship_goods          VALUES('92M7Y6O','SunFire V40z',2)";      SqlConnection con = new SqlConnection(conString);      SqlCommand command = new SqlCommand(query);      command.Connection = con;      Console.WriteLine("Opening connection");      con.Open();      Console.WriteLine("Connected to Sql Server");      Console.WriteLine("Executing query");      command.ExecuteNonQuery();      Console.WriteLine("Finished query execution");      Console.WriteLine("Closing Sql Server connection");      command.Connection.Close();   } 

Compiling and running the .NET application produces the following output, shown in Listing 6-11:

Listing 6-11. Connecting to the Database

 Buildfile: build.xml init:      [echo] --- Building j2eedotnet.chapter9 --- prepare: compile-dotnet-retailer:      [exec] Microsoft (R) Visual C# .NET Compiler version 7.10.6001.4      [exec] for Microsoft (R) .NET Framework version 1.1.4322      [exec] Copyright (C) Microsoft Corporation 2001-2002. All rights             reserved. run-dotnet-retailer:      [echo] Running .NET Retailer      [exec] Opening connection      [exec] Connected to MySql      [exec] Executing query      [exec] Finished query execution      [exec] Closing MySql connection BUILD SUCCESSFUL Total time: 1 second 

Should you disable MySql database, you will see error messages that are followed up with a connection to the SQL Server. Listing 6-12 lists a snippet of the output:

Listing 6-12. .NET Data Access Adapter Application Output

 run-dotnet-retailer:      [echo] Running .NET Retailer      [exec] Opening connection      [exec] Unhandled Exception: Can't connect to MySql server on             'localhost' (10061)      [exec] Couldn't connect to the Warehouse_A, connecting to             Warehouse_B      [exec] Opening connection      [exec] Connected to Sql Server      [exec] Executing query      [exec] Finished query execution      [exec] Closing Sql Server connection      [exec] Result: -532459699 

The next sections look at the second example where the Data Access Adapter is implemented in Java.

Example 2: Java Data Access Adapter

The next task is to build the Java-based implementation of the Data Access Adapter. Notice that there are a fair amount of similarities between Java and .NET implementations. Before proceeding with development, the JDBC drivers for SQL Server and MySql need to be configured. To see the detailed configuration of Connector/J JDBC driver, see [MySql_Config]. To connect to the Microsoft SQL Server, the corresponding JDBC driver [SQLServer_JDBC] needs to be downloaded and installed. Add the following jars to the CLASSPATH:

 install_dir/lib/msbase.jar install_dir/lib/msutil.jar install_dir/lib/mssqlserver.jar 


The first step is to connect to the MySql database. Listing 6-13 shows Java code to connect to the Warehouse_A database, MySql server.

Listing 6-13. Java Method Connecting to Warehouse_A, MySql

 public static void main(String args[]) {     Connection con = null;     Statement stmt = null;     ResultSet rs = null;     try {       // Since we are not using a connection pool,       // we simply create a new connection       Class.forName("com.mysql.jdbc.Driver").newInstance();       con = DriverManager.getConnection(              "jdbc:mysql:///Warehouse_A", "root", ""); 

Now establish a similar connection to SQL Server. To specify a connection string, the following information is needed:

 jdbc:microsoft:sqlserver://hostname:port     [;property=value...] 

Where property=value is required for the database name and user account:

 Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); Connection conn = DriverManager.getConnection ("jdbc:microsoft:sqlserver://Warehouse_B:1433;User=sa;Password=admin"); 

Listing 6-14 lists content of the Java main method that incorporates details of accessing the database.

Listing 6-14. Java Data Access Adapter Connecting to Warehouse_B, Microsoft SQL Server

 stmt = con.createStatement();    String query1 = new String(        "INSERT INTO ship_goods         VALUES('92558UYY6O','SunFire V40z',2)");    stmt.executeUpdate(query1);    stmt.close();    stmt = con.createStatement();    String query2 = new String(        "INSERT INTO ship_goods         VALUES('83545HYT567Y','SunFire V20z',1)");    stmt.executeUpdate(query2);    stmt.close();    System.out.println("Items           Quantity");    stmt = con.createStatement();    rs = stmt.executeQuery("SELECT desrc,qty FROM ship_goods");    while (rs.next())       System.out.println(rs.getString("desrc") + "       " +           rs.getInt("qty")); 

Executing the application produces the output listed in Listing 6-15:

Listing 6-15. Java Data Access Adapter Application Output, MySql Database

 >ant run-java-retailer Buildfile: build.xml init:      [echo] --- Building j2eedotnet.chapter9 --- prepare: compile-java-retailer:      [echo] --- Compiling Java Retailer application ---      [javac] Compiling 1 source file to             C:\a_book\Chapter6_DBSync\chapter7\classes run-java-retailer:      [echo] --- Running Java Retailer application ---      [java] Connection to Warehoues_A is established      [java] Items           Quantity      [java] SunFire V40z       2      [java] SunFire V20z       1 BUILD SUCCESSFUL Total time: 3 seconds 

Should MySql be disabled, you will be automatically connecting to SQL Server representing Warehouse_B, as shown in Listing 6-16:

Listing 6-16. Java Data Access Adapter Application Output, SQL Server

 init:      [echo] --- Building j2eedotnet.chapter9 --- prepare: compile-java-retailer:      [echo] --- Compiling Java Retailer application ---      [javac] Compiling 1 source file to             C:\a_book\Chapter6_DBSync\chapter7\classes run-java-retailer:      [echo] --- Running Java Retailer application ---      [java] Cannot connect to Warehouse_A, connecting to Warehouse_B      [java] Connection to Warehouse_B is established      [java] Items           Quantity      [java] SunFire V20z       1      [java] SunFire V40z       2 BUILD SUCCESSFUL 

What has been shown in the preceding code listings are implementations of an Adapter strategy. Java and .NET applications can share an adapter or use different adapters, depending on the Integration tier design.

Database connectivity is often accompanied by requirements to connect to legacy systems. Both synchronous and asynchronous integrations are used to connect to legacy applications depending on the scenario. A CRM system may incorporate user information pulled synchronously during use session, while an HR batch update typically happens asynchronously. The next section covers interoperability content related to the synchronous legacy integration. Asynchronous integration is discussed in detail in Chapter 10, "Resource Tier Asynchronous Integration."




Java EE and. Net Interoperability(c) Integration Strategies, Patterns, and Best Practices
Java EE and .NET Interoperability: Integration Strategies, Patterns, and Best Practices
ISBN: 0131472232
EAN: 2147483647
Year: N/A
Pages: 170

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net