The Benefits of SQLj: Replacing JDBC Code wit...

来源:百度文库 编辑:神马文学网 时间:2024/04/30 04:30:02
The Benefits of SQLj: Replacing JDBC Code with SQL
byMika Rinne
07/23/2002
The Benefits of SQLj: Replacing JDBC Code with SQL
By Mika Rinne
This month I'm going to look at some of the things I found in those days when I studied the use of SQLJ with WebLogic 6.1.
I got into the subject because I needed to go through a lot of existing JDBC code. As you may know, JDBC code is not the easiest to read, which made me start to think about embedded SQL, because of its better readability compared to JDBC.
In the past, I got used to writing applications on BEA's Tuxedo application server using the C language and embedded SQL, namely PRO*C, Oracle's name for their embedded SQL in C. I recalled that it worked nicely and had some very nice features like compilation time syntax checking and readability, features that JDBC is, obviously, lacking.
That got me studying SQLj, which is the name for embedded SQL in Java and which you can use, for example, with Oracle databases. I found lots of potential uses for writing SQL code instead of JDBC in Java, such as building Enterprise JavaBeans. In this article, when I talk about SQLj, I mean the implementation of SQLj from Oracle release 8.1.7.
Basics
First of all, embedded SQL means placing your SQL statements directly into your Java without using String objects (and without a bunch of other objects from the JDBC API), in contrast to JDBC. That gives you better readability for your code because the statements are pretty much like those you can issue from SQL*Plus or other SQL tools. For example:
#sql select ENAME, SAL from EMP order by ENAME;
After placing these commands in your code, you need to precompile the source code into a .java source, giving you the second important feature in SQLj, which is the compilation time syntax checking. In contrast to SQLj, in JDBC you need to compile and deploy your JDBC application, start the server, and run the application just to find out that the syntax of the SQL statement is incorrect. In SQLj, however, you don't necessarily have to carry out all that, since you'll get the error in precompilation time for syntax incorrectness. That said, I must add that the syntax checking could be much better - in most cases you find out about your SQL syntax errors during runtime.
There might also be a third reason for using SQLj: the performance. Some people say that it's better when compared to JDBC, but since I didn't do any tests and didn't measure it, I can't say. But according to the tests I did with EJBs, I can say the performance is certainly acceptable.
In order to write a SQLj-based Java application you first have to create a .sqlj source file like MyClass.sqlj, which contains the embedded SQL, and then compile it to a .java file, in this case MyClass.java, using the SQLj precompiler. Finally, the MyClass.java source file is compiled into a Java class file for execution, MyClass.class, accordingly.
The SQLj compiler is logically named 'sqlj' and is capable of not only precompiling the embedded SQL, but also of compiling the Java source into a Java class or classes. Alternatively, you can execute your own java compilation phase after the precompilation if you are explicitly setting the sqlj not to compile classes with the -compile option set to "false" (there's also a lot of other options as well). The procedure is as follows (as seen on the command line in Windows 2000):
\> set CLASSPATH=./lib/translator.zip;./lib/runtime.zip \> sqlj MyClass.sqlj
or
\> set CLASSPATH=./lib/translator.zip;./lib/runtime.zip \> sqlj -compile=false MyClass.sqlj \> javac MyClass.java
This will create MyClass.class in both cases, with the exception that in the first example the "default" Java compiler is used and in the latter the explicitly specified javac Java compiler from Sun's JDK is used. The latter also usually provides better output than the former in case of errors in the java source according to testing, especially when using Ant for building (see Building the EJB Using Ant later in this article).
Example One: A Local Class
The first example is the source code for the MyClass, which demonstrates the use of a SQL query we defined earlier and the use of the WebLogic oci driver for Oracle within SQLj. The implementation could be as shown in Listing 1.
Listing 1
import java.sql.*; import java.util.*; import oracle.sqlj.runtime.Oracle; #sql iterator MyIterator (String, double) ; public class MyClass { public static void main(String[] args) { try { Properties props = new Properties(); props.put("user", "scott"); props.put("password", "tiger"); props.put("server", "MJR"); Driver ociDriver = (Driver) Class.forName("weblogic.jdbc.oci.Driver").newInstance(); DriverManager.registerDriver(ociDriver); Connection conn = ociDriver.connect("jdbc:weblogic:oracle", props); Oracle.connect(conn); MyIterator myIterator = null; String ename = null; double sal = 0; #sql myIterator = { select ENAME, SAL from EMP order by ENAME }; while (true) { #sql { FETCH :myIterator INTO :ename, :sal }; if (myIterator.endFetch()) break; System.out.println(ename + " " + sal); } myIterator.close(); Oracle.close(); } catch (Exception e) { e.printStackTrace(); } } }
When compiled and run from command line, the result would look like Listing 2.
Listing 2
\>java -classpath %CLASSPATH%;. MyClass Starting Loading jDriver/Oracle ..... ADAMS 1100.0 ALLEN 1600.0 BLAKE 2850.0 CLARK 2450.0 FORD 3000.0 JAMES 950.0 JONES 2975.0 KING 5000.0 MARTIN 1250.0 MILLER 1300.0 SCOTT 3000.0 SMITH 800.0 TURNER 1500.0 WARD 1250.0
Before running it you need to set the WebLogic classpaths, which you can do by running the config\examples\setexamplesenv.cmd from your WebLogic 6.1 installation directory. If there had been errors in the SQL, the precompiler might have detected them, for example:
\>sqlj -compile=false MyClass.sqlj MyClass.sqlj:24.9-24.55: Error: SQL statement could not be categorized. Total 1 error.
Although, as I said earlier, this is not a typical case; when you use SQLj you will still usually find out about your syntactical errors during runtime.
Example Two: An EJB
While the first example is a static class and run locally, our second example demonstrates the use of SQLJ within an Enterprise JavaBean (EJB). There are two major areas of difference between a local class and a class (or classes) run on the server side inside WebLogic, like an EJB: Multithreading and concurrency Pooled database connections
Although these may be quite obvious to most readers, let's go through them quickly. First, EJBs are always executed within threads, unlike most local classes, which means that clients execute the same piece of code simultaneously (within the same JVM, i.e., within the WebLogic instance).
Second, since the same piece of code runs simultaneously, we need to have pooled database connections for maximum performance. Otherwise, we would either run out of available database connections (i.e., exceed the maximum number of connections from the database point of view) or, if there is only one connection (and synchronization is used), the performance would be very bad.
In SQLj we can do multithreading by first creating a so-called context and then using that context in our SQLj statements, for example:
#sql context MyContext; #sql [myContext] myIterator = { select ENAME, SAL from EMP order by ENAME };
Before you can use the context, it needs to be created from a pooled connection using a WebLogic oci pool driver and a data source named "demoPool" of an EJB as follows:
InitialContext initCtx = new InitialContext(); DataSource ds = (javax.sql.DataSource) initCtx.lookup("java:comp/env/jdbc/demoPool"); MyContext myContext = new MyContext(Oracle.getConnection(ds.getConnection())); initCtx.close();
If you aren't familiar with WebLogic data sources, take a look at the WebLogic EJB examples and documentation for more information.
The EJB implementation using the issues described above could be as shown in Listing 3. The query() method of this EJB returns a Vector of Emp records with ename and sal that we saw in the first example to the calling client.
Listing 3
import java.sql.*; import java.util.*; import java.io.Serializable; import javax.ejb.*; import javax.naming.*; import javax.sql.DataSource; import oracle.sqlj.runtime.Oracle; #sql context MyContext; #sql iterator MyIterator (String, double) ; public class MyBean implements SessionBean { private SessionContext ctx; public void ejbActivate() {} public void ejbCreate () throws CreateException {} public void ejbRemove() {} public void ejbPassivate() {} public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } public Vector query() { MyContext myContext = null; try { myContext = init(); MyIterator myIterator = null; Vector v = new Vector(); String ename = null; double sal = 0; #sql [myContext] myIterator = { select ENAME, SAL from EMP order by ENAME }; while (true) { #sql { FETCH :myIterator INTO :ename, :sal }; if (myIterator.endFetch()) break; v.addElement(new Emp(ename, sal)); } myIterator.close(); return v; } catch (SQLException sqle) { throw new EJBException(sqle); } finally { cleanup(myContext); } } private MyContext init() throws SQLException { InitialContext initCtx = null; try { initCtx = new InitialContext(); DataSource ds = (javax.sql.DataSource) initCtx.lookup("java:comp/env/jdbc/demoPool"); MyContext myContext = new MyContext(Oracle.getConnection(ds.getConnection())); return myContext; } catch(NamingException ne) { throw new EJBException(ne); } finally { try { if(initCtx != null) initCtx.close(); } catch(NamingException ne) { throw new EJBException(ne); } } } private void cleanup(MyContext myContext) { try { myContext.close(); Oracle.close(); } catch (Exception e) { throw new EJBException (e); } } }
Building the EJB Using Ant
The easiest way to compile and build the example MyBean EJB is to use Ant, which comes with WebLogic Server examples. I extended Ant's build.xml definition file a bit in order to execute the SQLj precompilation before the Java compilation (see Listing 4).
Listing 4

You must also include the step to the target name="all" in the build.xml, for example:

You should also set some properties for the task at the beginning of the build.xml:

(These jar files must also exist in the "libs" directory under your project directory.)
Running the EJB Client
After building the EJB with Ant and deploying it to WebLogic Server, you can run the EJB client for testing. There's nothing special in the client to any other EJB client, since all SQLj code relies on the server side in the EJB.
However, I extended one of the EJB clients that come with the WebLogic examples a bit in order to make it multithreaded for optimal testing. I modified the client so it launches 50 client threads that will then call the query() method of the EJB. Then I started a couple of clients running simultaneously on different JVMs on my laptop, and had no problems with the EJB returning a response relatively quickly to each of the calling client threads.
Conclusion
The testing showed that during the execution the number of pool connections grew to the maximum number of EJBs specified in the pool (set to 10 in the deployment descriptor), but after all threads had executed, the number of reserved pool connections dropped to zero. Thus we can say that the connection pooling worked just as it should with our example SQLj EJB.
A complete example of an SQLj EJB can be downloaded herehttp://ftpna2.bea.com/pub/downloads/Rinne0105.zip.
More information about SQLj can also be found on Oracle's Web site with the SQLj compiler version 8.1.7 used in these examples.
Copyright © 2002 SYS-CON Media, Inc.