UsageJing-SQL should be fairly simple to use and extend. This example will look at using the library outside of any container. Getting to work in a container is even easier. ConfigurationJing-SQL uses one XML file to store the SQL in. Currently I've been using the "vsql" extension for "Velocity SQL", but what you call the file is sort of up to you. The important part is what's inside. Let's look at an example: <?xml version="1.0" encoding="ISO-8859-1"?> <sql-manager> <query id="customer"> SELECT NAME, ADDRESS, PHONE FROM CUSTOMER_TABLE WHERE ORDER_NUMBER = ${orderNumber} </query> </sql-manager>
In this simple example all we have is one query, "customer."
The reference
The CodeLet's assume that we call the file above "sql-manager.vsql" and we place it in a directory named "WEB-INF." Now let's look at the code that uses this SQL. There are only two interfaces you need to concern youself with:
The
public interface SQLManager { public SQLEvaluator getSQL(String key); }
If you're using this in a standalone environment, then you'll
need to directly access an implementation such as the
import org.jadetower.sql.impl.AvalonSQLManager; ... AvalonSQLManager sqlManager = new AvalonSQLManager(); // make sure we configure it! sqlManager.configure("WEB-INF/sql-manager.vsql");
Now you'll want to use an
SQLEvaluator sql = sqlManager.getSQL("customer"); sql.set("customerNumber",new Integer(100001)); ResultSet rs = sql.executeQuery(databaseConnection); But wait! It gets better! Suppose we create a java bean that represents our query results. Wouldn't it be nice if it were automatically populated? Say no more... SQLEvaluator sql = sqlManager.getSQL("customer"); sql.set("customerNumber",new Integer(100001)); List customers = (List) sql.executeQuery( databaseConnection, org.proj.CustomerBean.class, null); for(int i=0; i < customers.size(); i++){ CustomerBean customer = (CustomerBean) customers.get(i); ... }
This example assumes that
But what about bind variables? For those that prefer the bind variable approach, you can write your SQL as follows: <?xml version="1.0" encoding="ISO-8859-1"?> <sql-manager> <query id="customer"> SELECT NAME, ADDRESS, PHONE FROM CUSTOMER_TABLE WHERE ORDER_NUMBER = ? </query> </sql-manager>
You must then set an attribute named
You can use
One final note, when you get a
For more info, see the JavaDocs. |