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
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
In his session at @ThingsExpo, Dr. Robert Cohen, an economist and senior fellow at the Economic Strategy Institute, presented the findings of a series of six detailed case studies of how large corporations are implementing IoT. The session explored how IoT has improved their economic performance, had major impacts on business models and resulted in impressive ROIs. The companies covered span manufacturing and services firms. He also explored servicification, how manufacturing firms shift from se...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.