Tuesday, May 29, 2012

Native SQL query using Hibernate causes ArrayIndexOutOfBounds

Problem:


In hibernate I was trying to use a native SQL query to retrieve records from the database when I encountered an ArrayIndexOutOfBoundsException on the following piece of code:


                String sql = "SELECT * FROM fcs f"
                SQLQuery query = session.createSQLQuery(sql)                
                //query.setString(0, barcode.toString())
                try {
                    list = query.list()   // <-- ERROR HERE
                } catch(Exception e) {
                    //e.printStackTrace()
                    logger.error(e)
                    ByteArrayOutputStream baos = new ByteArrayOutputStream()
                    PrintWriter pw = new PrintWriter(baos)
                    e.printStackTrace(pw)
                    pw.close()
                    byte[] array = baos.toByteArray()
                    String exp = new String(array)
                    logger.error(exp)
                }

As you can see, I managed to dump out the stacktrace which looked as follows:


Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
   at org.hibernate.type.TypeHelper.disassemble(TypeHelper.java:146)
   at org.hibernate.cache.StandardQueryCache.put(StandardQueryCache.java:106)

The important thing to notice about this stacktrace is that the error happens out of the StandardQueryCache.

Solution:


In grails, by default the standard query cache was enabled. To workaround the issue, I've disable it in the DataSource.groovy file as follows:


hibernate {
    cache.use_second_level_cache = false
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}

References:


No comments:

Post a Comment