Tuesday, April 7, 2009

java.sql.PreparedStatement with named params using static class

I have been programming a system wich uses exclusively JDBC queries. No ORM tools are used. All of the SQL queries are with java.sql.PreparedStatment using "?" (question marks) for data insertion. The resons for this are not the topic of this post. Since I am in this environment and rely wanted named parameters in my SQL queries I just went out and looked for these on the web. I found this.

Now this requires to make a wrapper to java.sql.PreparedStatement. But the system is quite large and it is better for me to make static calls only. So I coded my own static methods for achiving the same goal. The code is found at the bottom of this post and you can use it like this:


Connection con = ds.getConnection("xxx");
String sql_p = "SELECT * FROM table WHERE table.ID=:sid ORDER BY ID DESC ";
// if you don't have null values in params list then make hashmap with param values
HashMap param_map = new HashMap(); param_map.put("sid", 1);
// if you might have null values in params list then make hashmap like this
HashMap param_map = new HashMap(); param_map.put("sid", new Object[] {null, java.sql.Types.INTEGER});
// make indexed query (with ? markers)
String sql_i = SQLHelper.namedParamParseSQL(sql_p, param_map);
PreparedStatement stmt = con.prepareStatement(sql_i);
// assign statement params
stmt = SQLHelper.namedParamAssign(stmt, param_map, sql_p);


The SQLHelper class can be found here:

package util;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;

import ee.eschool.exceptions.DWRException;

/**
* SQL Helper functions
*
* 1. Static class for named params in JDBC SQL.
* Original code here: http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html?page=1
* Usage instructions: http://imlostinit.blogspot.com/2009/04/javasqlpreparedstatement-with-named.html
* Usage sample:
* Connection con = ds.getConnection("xxx");
* String sql_p = "SELECT * FROM table WHERE table.ID=:sid ORDER BY ID DESC ";
* // if you don't have null values in params list then make hashmap with param values
* HashMap param_map = new HashMap(); param_map.put("sid", 1);
* // if you might have null values in params list then make hashmap like this
* HashMap param_map = new HashMap(); param_map.put("sid", new Object[] {null, java.sql.Types.INTEGER});
* // make indexed query (with ? markers)
* String sql_i = SQLHelper.namedParamParseSQL(sql_p, param_map);
* PreparedStatement stmt = con.prepareStatement(sql_i);
* // assign statement params
* stmt = SQLHelper.namedParamAssign(stmt, param_map, sql_p);
*
* @author erkulas
*
*/
public class SQLHelper {

/**
* Parse SQL query with named params and return SQL query with indexes .
*
* @param sql_query SQL query string with named parameters (like :param )
* @return parsed SQL query with indexes ( ? ) in the place of params ( :param )
*/
public static String namedParamParseSQL(String sql_query) {
int length=sql_query.length();
StringBuffer parsedQuery=new StringBuffer(length);
boolean inSingleQuote=false;
boolean inDoubleQuote=false;
for(int i=0;i<length;i++) {
char c=sql_query.charAt(i);
if(inSingleQuote) {
if(c=='\'') {
inSingleQuote=false;
}
} else if(inDoubleQuote) {
if(c=='"') {
inDoubleQuote=false;
}
} else {
if(c=='\'') {
inSingleQuote=true;
} else if(c=='"') {
inDoubleQuote=true;
} else if(c==':' && i+1<length && Character.isJavaIdentifierStart(sql_query.charAt(i+1))) {
int j=i+2;
while(j<length && Character.isJavaIdentifierPart(sql_query.charAt(j))) { j++; }
String name=sql_query.substring(i+1,j);
c='?'; // replace the parameter with a question mark
i+=name.length(); // skip past the end of the parameter
}
}
parsedQuery.append(c);
}
return parsedQuery.toString();
}

/**
* Parses sql_query and returns a list of params with "param_idx" value indicating the param order in SQL.
*
* @param sql_query SQL query string with named parameters (like :param )
* @param param_map HashMap of parameter values
* @return List of HashMaps with indexes according to their order in the sql_query
*/
public static List<HashMap&rt; namedParamGetIdx(String sql_query, HashMap param_map) throws SQLException {
List<HashMap&rt; indexList = new ArrayList();
int length=sql_query.length();
StringBuffer parsedQuery=new StringBuffer(length);
boolean inSingleQuote=false;
boolean inDoubleQuote=false;
int index=1;
Object sqltype, val;
for(int i=0;i<length;i++) {
char c=sql_query.charAt(i);
if(inSingleQuote) {
if(c=='\'') {
inSingleQuote=false;
}
} else if(inDoubleQuote) {
if(c=='"') {
inDoubleQuote=false;
}
} else {
if(c=='\'') {
inSingleQuote=true;
} else if(c=='"') {
inDoubleQuote=true;
} else if(c==':' && i+1<length && Character.isJavaIdentifierStart(sql_query.charAt(i+1))) {
int j=i+2;
while(j<length && Character.isJavaIdentifierPart(sql_query.charAt(j))) { j++; }
String name=sql_query.substring(i+1,j);
c='?'; // replace the parameter with a question mark
i+=name.length(); // skip past the end of the parameter
if(param_map.get(name)!=null) {
if(param_map.get(name) instanceof Object[]) { val = ((Object[])param_map.get(name))[0]; } else { val = param_map.get(name); }
HashMap hm = new HashMap(); hm.put("param_name", name); hm.put("param_val", val); hm.put("param_idx", index);
sqltype=java.sql.Types.VARCHAR;
if((param_map.get(name) instanceof Object[]) && (((Object[])param_map.get(name))[1]!=null)) { sqltype=((Object[])param_map.get(name))[1]; }
else if(val==null) { throw new SQLException("Param null and no SQLType specified."); }
hm.put("param_sqltype", sqltype);
indexList.add(hm);
index++;
}
else { throw new SQLException("Param "+name+" not found in mapping."); }
}
}
}
return indexList;
}

/**
* Assign PreparedStatement with the values from param_map according to their order in sql_p .
*
* @param stmt The PreparedStatement instance to be used.
* @param param_map An HashMap with parameter values.
* @param sql_p SQL query with named parameters ( :param )
* @return Returns the PreparedStatement with the params assigned.
*/
public static PreparedStatement namedParamAssign(PreparedStatement stmt, HashMap param_map, String sql_p) throws SQLException {
List<HashMap&rt; param_idx = namedParamGetIdx(sql_p, param_map);
return namedParamAssign(stmt, param_idx);
}

/**
* Assign PreparedStatement with the values from param_map according to their order in sql_p .
*
* @param stmt The PreparedStatement instance to be used.
* @param statement_idx_list List of params .
* @return Returns the PreparedStatement with the params assigned.
*/
public static PreparedStatement namedParamAssign(PreparedStatement stmt, List<HashMap&rt; statement_idx_list) {
for(Integer c=0; c<statement_idx_list.size(); c=c+1) {
Object val=statement_idx_list.get(c).get("param_val");
Integer idx=(Integer)statement_idx_list.get(c).get("param_idx");
Integer sqltype=(Integer)statement_idx_list.get(c).get("param_sqltype");
try {
if(val==null) { stmt.setNull(idx, sqltype); }
else if(val instanceof String) { stmt.setString(idx, (String)val); }
else if(val instanceof Integer) { stmt.setInt(idx, (Integer)val); }
else if(val instanceof Long) { stmt.setLong(idx, (Long)val); }
else if(val instanceof Boolean) { stmt.setBoolean(idx, (Boolean)val); }
else if(val instanceof java.util.Date) { stmt.setDate(idx, new java.sql.Date( ((java.util.Date)val).getTime() ) ); }
else if(val instanceof java.sql.Date) { stmt.setDate(idx, (java.sql.Date)val); }
} catch (SQLException e) { e.printStackTrace(); }
}
return stmt;
}


}

Saturday, February 28, 2009

JavaRebel Licensing change

I've been trying out JavaRebel for some time now. It works like a charm if you take into account its features/limitations while developing.

Now Zeroturnaround is changing it's pricing/licecing model . Until March 9 2009 you can still buy perpetual licences for $100. Those licenses will still be in effect after that date but you can not buy new perpetual licenses after that date. They will only offer annual licenses.

Since I still had'nt bought JavaRebel I just went out and did it. Now I am a owner of JavaRebel perpetual license and just hoping that Zeroturnaround will not do some kind of draconian licensing stunt. The perpetual license does include updates but they could just release a new product instead.


PS: Like me, Zeroturnaround is of Estonian origin. On pure technical merits I would call the innovation of JavaRebel on par with Skype . This is just an amazing product that the big ones (Sun/IBM/...) have omitted.

Saturday, February 21, 2009

Struts 2 Ajax with JSON plugin

Heurekaaa!

I've managed to get the Struts 2 JSON plugin working. Surprisingly the thing works out of the box. Just initialize all of the stuff that you have there in the howto and you have Ajax with JSON data-transport. I even managed to integrate the example right into my application.

Maybe I'll be more verbose on the subject next post but i'ts 2 AM and I've earned my sleep for today.


PS: While researching the subject I also found this very recent presentation about JSON/Bayeoux/Comet generally and the Weblogic "Comet" API.

Thursday, February 12, 2009

Copying Hibernate objects

Today I had to copy my data in a MySQL database. My application uses Spring/Hibernate. Basically I had some rows in a database in multiple tables with relations and needed to make a copy of those with some of the data modified in the process.

Well I am an "ex" PHP guy, so ofcourse the most straightforward way should be the correct way - shouldn't it! Lets see. Our application uses Hibernate with POJO-s and manages all the data on object level. And I don't want to designate all the fields of a row (=properties of the object) one by one when copying. So I should just:
1. query the object form DB
2. give the object a new identity (reset the ID-s of that object with new ones and/or clone the object ) .
3. modify the new object according to our requirements (assign new relations, set some relations null, ...)
4. insert the object back to DB
Should be easy ... well not quite.

Hibernate keeps track of my POJO-s in a draconian CIA way, not a straightforward PHP way :). When I nullify the ID-s Hibernate just changes the existing object and since it is the same object the DB will be UPDATE when executing em.merge() or em.persist() . So I relly needed to eather clone the object using the "cloneable" interface or detach the object and modify the detached object. I could detach the object by serializing it or closing the EntityManager session but both methods are a bit too cumbersome to me for this simple task. I just need a simple way to copy database rows, something like this:

Object new_obj=copy(old_obj); em.persist(new_obj); .

So here comes the Hibernate3BeanReplicator .It does all the dirty work and still leaves me in control of the copying process. Like this:


Hibernate3BeanReplicator r = new Hibernate3BeanReplicator(null, null, null);
Object o_obj_new = r.copy(o_obj);
o_obj_new.setSomeRelation(null);
o_obj_new.setSomeIntField(0);
o_obj_new.setID(null); // we need to nullify the ID so that Hibernate will treat the result as a new object not a detached instance of an existin object
em.persist(o_obj_new);

Thursday, January 29, 2009

Hello world!

Hello world!

This is my real first post here on blogger.com . I have been keeping my own blog in one of my servers Roller install and it's been boring - no visitors :P . So I'll be submitting all my old postings and then start posting here from now on.

All the best.

Sunday, January 25, 2009

Struts 2/dojo datepicker tag sucks with non US locale

I have been messing around with Struts 2 datepicker tag. The goal is to submit date and time for a date field.

You make a Date field in Struts 2 action object. And you put in your JSP the datepicker tag like this:

<s:datetimepicker name="date_planned_date" label="" displayformat="dd.MM.yyyy" type="date" value="%{date_planned_date}" />
Now it is important not to get the locales mixed up. So I have been forcing the locale on EVERY form like that:

<s:hidden name="request_locale" value="et_EE" />
And just in case I have my locale also specified in struts.xml:

<constant name="struts.locale" value="et_EE" />
Anyway this setup doesn't work, because datepicker is not able to parse the date in the "value" param. So we omit the value param and things start working. But in our case we NEEDED the value param, because we also wanted to submit time but we didn't want to use the built-in TIME picker, but instead a text-field.

So the solution for us was to make two separate String fields in our Struts 2 application to wich we submited the date and time part of the datetime. And upon saving to DB we constructed the date out of those string fields.

With s:datepicker any "out of the box" setup for i18n does not work and as always with Struts customizations need a lot of extra coding. The datepicker tag should just work with ANY date it is given with the "value" param. Currently it does not - Java's hard work and no fun!

Wednesday, January 21, 2009

Hibernate query logging with binded parameters

I've been struggling with Hibernate queries before. Now I took the time to research this and ended up with another fucked up situation in Java world. There really is no "best practice" AND easy way of capturing queries (HQL/SQL) that are executed on DB in Hibernate.

Basically there is these alternatives:

1. Hibernate built in options ( a good description here )
2. Use Jamon, P3Spy or another similar tool
3. Custom query translator for Hibernate ( see here )
4. SQL database general query log (if applicabel to your database)

Among these only P3Spy, Custom translator, and query log have the ability to display binded query parameters within the query. So that you can copy/paste the query to your SQL tool/terminal. P3Spy project is on ice and custom query translators don't really sound like "best practice". General query log depends on DB. And should you really be spending your time programming custom translators?

Not least but last: the methods above display ALL the queries executed! When using Hibernate built-in options the data flow is way too moch for a web page that has maybe 20 queries on page load.

So there is NO NICE way of debugging that one runaway query in Hibernate/JPA. This is just NOT ACCEPTABLE. We need to be able to turn debugging on/off in Java code when making queries. Heck, my custom built data layer in PHP has the ability!