24
Wed, Apr
0 New Articles

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..

Michael Floyd

Michael J. Floyd is the Vice President of Engineering for DivX, Inc.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: