Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

The Benefits of SQLj

The Benefits of SQLj

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. When compiled and run from command line, the result would look like Listing 2. 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.

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). You must also include the step to the target name="all" in the build.xml, for example:

<target name="all" depends="clean,
init, sqlj, compile_ejb, jar_ejb,
ejbc,
compile_webapp,
compile_client"/>

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

<property name="libs" value="${source}/lib"/>
<property name="sqljlib1"
value="${libs}/translator.zip"/>
<property name="sqljlib2" value="${libs}/runtime12.zip"/>

(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 found on the WLDJ Web site at www.sys-con.com/weblogic/sourcec.cfm. The example can be also found on BEA's developer site http://dev2dev.bea.com under WebLogic Server examples.

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.

More Stories By Mika Rinne

Mika Rinne is a senior consultant with BEA Systems Inc. He has been programming since he was 13 and in 1995 built an Internet and BEA
TUXEDO-based online ticket-selling service, the first of its kind in Scandinavia.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, will discuss some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he’ll go over some of the best practices for structured team migrat...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they bu...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.