Java Journal: SQLJ to the Rescue

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
If you're writing applications in Java, chances are you're storing and retrieving data from a relational database. Although there are other was of doing it, you are probably using JDBC because it is the easiest--or should I say least painful--way to communicate with a relational database. The core of JDBC is the PreparedStatement class. This class allows you to invoke SQL commands and bind in local Java variables for querying, updating, and deleting information in your database. However, PreparedStatements can become unwieldy and difficult to read. Additionally, even the slightest typo causes nasty runtime errors. Tie this with the fact that a declarative language such as SQL is difficult to read, and you have a problem. If that isn't motivation enough to look for an alternative method, there are issues with JDBC allowing you to execute SQL commands directly against a database. The problem is that not a single major database vendor fully supports the SQL-92 standard, and most have added their own proprietary extensions. So if you ever need to port your application to another database platform, you will have to rewrite at least some, if not all, your SQL that deals with often-proprietary implementations such as dates and outer joins. The best solution that I have found to all these Java and SQL interoperability problems is SQLJ.

Just like SQL and Java, SQLJ is a language and therefore has syntax and grammar rules, just like any other language. SQLJ source files look just like Java source files with some new types of statements, and use they use .sqlj as the extension on their filenames. In keeping with the Java "write once, run anywhere" theme, SQLJ source files can be written once and run against multiple databases without modification. However, to achieve this, you will need to acquire a SQLJ development tool for each of your target databases. Note that this is similar to the way that JDBC drivers work, in that each vendor supplies its own implementation of a standard interface.

SQLJ development tools consist of two components: a SQLJ Translator component and a SQLJ Runtime component. Those of you who are familiar with C/C++ will notice the similarities between the SQLJ Translator and the C/C++ preprocessor. To use SQLJ in your application, you first create one or more SQLJ source files, which are simply text files with a .sqlj extension. You then invoke the SQLJ Translator, which--true to its name--translates SQLJ source files to Java source files that contain references to SQLJ Runtime components. These Java source files, just like any other Java source files, can be compiled with any standard Java compiler to produce .class files.

So far, this just looks like a couple of extra useless steps. To really analyze the differences between a conventional PreparedStatement query and a SQLJ query, we will need a couple of examples, but first we will need a couple of database tables:

Department Table
CREATE TABLE department
(
  department_id NUMBER,
  name VARCHAR(20)
);

Employee Table
CREATE TABLE test_employee
(
  employee_id NUMBER,
  name VARCHAR(20),
  department_id NUMBER
);

Figure 1 shows a traditional JDBC framework for connecting to the database, along with a simple query to select all the employees in a particular department and print them out:

// JDBCConnectionExample.java

import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.OracleDriver;

public class JDBCConnectionExample
{
  public static void main(String[] argv)
  {
    new JDBCConnectionExample();
  }

  private Connection connection = null;

  public JDBCConnectionExample()
  {
    connectToTheDatabase();
    queryDatabase();
    disconnectFromTheDatabase();
  }

  private void connectToTheDatabase()
  {
    try
    {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      connection = DriverManager.getConnection("yourDatabaseUrl", "user",
                                               "password");
    )
    catch(SQLException e)
    {
      System.out.println(e.toString());
    }
  }

  private void disconnectFromTheDatabase()
  {
    try
    {
      connection.close();
    }
    catch(SQLException e)
    {
      System.out.println(e.toString());
    }
  }

  private void queryDatabase()
  {
    String sql = "SELECT emp.name AS employee_name, " +
                 "emp.employee_id, " +
                 "dep.name AS department_name " +
                 "FROM employee emp, department dep " + 
                 "WHERE emp.department_id = dep.department_id " +
                 "AND dep.department_id = ? " +
                 "";
    try
    {
      PreparedStatement pstmt = connection.prepareStatement(sql);
      pstmt.setInt(1, 12345);
      ResultSet rs = pstmt.executeQuery();

      while (rs.next())
      {
        String employeeName = rs.getString("employee_name");
        String employeeId = rs.getString("employee_id");
        String departmentName = rs.getString("department_name");
        System.out.print(employeeName + " ");
        System.out.print(employeeId + " ");
        System.out.println(departmentName);
      }
    }
    catch (Exception e)
    {
      System.out.println(e.toString());
    }
  }
}

Figure 1: This JDBC framework connects to the database, and the query selects a list of employees and prints it.

In the previous example, we have a class containing a main() routine, which instantiates an object of the class JDBCConnectionExample. The constructor then invokes three private methods in succession to connect to the database, query the database, and then close the database connection. Overall, it's a pretty simple process, but it does have some drawbacks.

The first drawback is all the clutter in the actual construction of the SQL statement itself. This simple two-table join query contains 26 characters more than would be necessary if the same query were run from SQL*PLUS or some other command line SQL tool. And even forgetting to pad out the end of a line will lead to a runtime error, which, of course, you would catch with one or more of your JUnit tests (see "JUnit: An Automated Test Runner for Java" for more information.)

The second drawback is how you assign parameters to the PreparedStatement: by using a combination of question marks (?s) and setInt(), setString(), setDate(), and other setXXX() methods. These work fine for simple queries like the one above. But what if you need to pass in a dozen or more values? It is very easy to make a mistake. Or what if you need to add a new parameter? You might have to shift many of the index numbers in the setXXX() methods. Also, since the value being set and the place where it is being set are often many lines apart, the exact purpose of the query is frequently obscured.

The third and often-overlooked drawback is that String objects are immutable, which means that each time two string are concatenated, a new String object is instantiated. So in the example, seven String objects are created--each successively larger. This is probably fine for small or infrequently run queries. But what if you have a 100+ line query that is running hundreds of thousands of times an hour? Note that you could also avoid this problem by applying a StringBuffer class.

Yet another drawback to the PreparedStatement method is that it uses a very tight version of string coupling to extract the data from the ResultSet. String coupling is where you tie two things together by a hard-coded String. The problem with String coupling is that errors are not detected until runtime and even small changes often have devastating cascade effects. In this case, the getXXX() methods of the ResultSet are coupled to the column names of either the database or the aliases assigned to them by the 'AS' clause of the SQL statement.

The final drawback to this method is that the SQL statement is parsed at runtime. So even if you correctly space and appending together the String, but then you misspell the name of a table or column, it will still compile without warnings or errors. In addition, if you are working with Enterprise JavaBeans (EJBs), you will need to deploy your Beans before you can test them. This can be a lengthy and frustrating way to discover a typo.

Figure 2 an example that implements the same functionality using SQLJ.

// SQLJConnectionExample.sqlj

import java.sql.*;
import java.util.*;
import oracle.sqlj.runtime.Oracle;

#sql iterator EmployeeIterator 
  (
    String employeeName, 
    String employeeId, 
    String departmentName
  );

public class SQLJConnectionExample
{
  public static void main(String[] argv)
  {
    new SQLJConnectionExample();
  }

  private Connection connection = null;

  public SQLJConnectionExample()
  {
    connectToTheDatabase();
    queryDatabase();
    disconnectFromTheDatabase();
  }

  private void connectToTheDatabase()
  {
    try
    {
      Oracle.connect(SQLJConnectionExample.class, "connect.properties");
    }
    catch(SQLException e)
    {
      System.out.println(e.toString());
    }
  }

  private void disconnectFromTheDatabase()
  {
    try
    (
      Oracle.close();
    }
    catch(SQLException e)
    {
      System.out.println(e.toString());
    }
  }

  private void queryDatabase()
  {
    try
    {
      int departmentId = 12345;

      EmployeeIterator iter;
      #sql iter = 
        {
          SELECT emp.name AS employeeName, 
                 emp.employee_id AS employeeId, 
                 dep.name AS departmentName 
          FROM test_employee emp, test_department dep 
          WHERE emp.department_id = dep.department_id 
          AND dep.department_id = :departmentId 
        };

      while (iter.next()) 
      {
        System.out.print(iter.employeeName() + " ");
        System.out.print(iter.employeeId() + " ");
        System.out.println(iter.departmentName());
      }
    }
    catch (Exception e)
    {
      System.out.println(e.toString());
    }
  }
}

Figure 2: Here, SQLJ implements the same functionality as the code in Figure 1.

Note that the code in Figure 2 requires two property files for connecting to the database: one for the SQLJ Translator and one for SQLJ Runtime. Although you can set lots of properties in these files, to start with you will just need to supply a database URL, user name, and password just as you would if you were making a getConnection() call to DriverManager to get a database connection.

You will notice that Figure 2 is patterned after Figure 1, with the same three private methods for connecting, querying, and closing the database connection. Besides the connect and disconnect statements, which are now making slightly different calls and using the properties file, you will notice two #sql directives, which act as flags to the SQLJ Translator. These flags signal that the following code (surrounded by parentheses) needs to be translated from SQLJ into Java. In this example, the first #sql directive is instructing the SQLJ Translator to create an Iterator that will be used later to hold the query results. The second #sql directive surrounds the SQL query statement. This new SQL query is free of all the garbage formatting characters of the PreparedStatement example and also replaces the ? with :departmentId, which tells the SQLJ Translator to use the local departmentId variable here. This process is known as binding or using a host variable, and it ties back to earlier embedded SQL languages. Note also that the data is now returned directly into an Iterator rather than into a ResultSet.

Now, let's see how SQLJ addresses each of the drawbacks we found in our PreparedStatement example. The first drawback was the clutter in the SQL statement itself, which we can plainly see has been resolved. The second drawback was the use of ?s to pass variables. Clearly, use of the host variable in the above example results in much cleaner code. This is even more apparent if the same host variable needs to be used more than once in the SQL statement. The third drawback was the creation and re-creation of String objects, which has been resolved, although that's not apparent from this example. You can take a look at the Java file that the SQLJ Translator produces if you are curious about how this was accomplished. The next drawback of the PreparedStatement was the tight string coupling when extracting data from the ResultSet. The string coupling problem has been completely resolved by the SQLJ Translator, which generates an Iterator object that encapsulates the ResultSet object. The most important side effect of this encapsulation is that the SQLJ Translator will detect any differences between the names of fields being defined as part of the Iterator and those being returned by the ResultSet. Finally-- and most importantly--is that by using a command line option and a parameter file, you can direct the SQLJ Translator to actually connect to the database and verify that your SQL statement is syntactically correct at translation/compile time. So you can spend more time coding and less time deploying and executing tests that are doomed to fail because of typos.

As with most technologies, there are some tradeoffs to using SQLJ. The first tradeoff is the initial setup time. It can take a little while to locate, download, and configure a SQLJ development tool for your database. The second tradeoff is that if you are using the SQLJ Translator to verify your SQL statements, it will be making lots of connections to your database, which can be a little time-consuming. However, catching errors at translation time rather than at runtime usually more than makes up for the extra time. The final tradeoff is that SQLJ cannot be used for dynamic queries, which are queries in which the structure of the query changes from one call to the next. An example of a dynamic query would be a query in which the list of columns that are selected changes at runtime.

A major concern that developers usually have about adopting a tool like SQLJ is whether it is standards-based or not. Well, you're in luck with SQLJ, which is governed by both ANSI and ISO standards. For more information, see the official SQLJ Web site. Also, all of the major database vendors have SQLJ development tools.

Conclusion

Java and SQL are both powerful languages, but integrating them together can be a daunting task. SQLJ can alleviate most common problems traditionally associated with embedding SQL in Java. SQLJ not only improves the appearance and readability of SQL embedded in Java, but can also be used to abstract away string coupling problems associated with ResultSets. Additionally SQLJ provides a more standard interface to a database than JDBC, so it can used to keep your application database neutral and thus easier to port against other database platforms. However, by far and away, the most compelling reason to use SQLJ is to catch errors at translation/compile time rather than at runtime.

Michael J. Floyd is an Extreme Programmer and the Software Engineering Technical Lead for DivXNetworks. He is also a consultant for San Diego State University and can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS