When utilizing the iBATIS framework you define your SQL Maps to perform the basic CRUD functionality and additional business logic for an individual item. Very often you will be only updating single objects at a time and this is great, but what happens on those occasions where you find yourself processing hundreds of objects at the same time. The simple answer Batch Processing.

Batch Processing is the execution of a set of SQL statements without any user intervention. In essence it takes a group of commands executes them one at a time and then returns the updated count. Well in most cases some drivers won’t return the actual update count and instead returns 0.

Below is a short tutorial on how to perform Batch Processing in Java utilizing the Spring and iBATIS frameworks. In the example we will define and implement the method processInBatch method that will handle the processing. It assumes you have basic knowledge of each of the frameworks and focuses strictly on how to setup batch processing.

Initial Setup

Lets start by assuming for this example that we have a table in our database called APPLICATION and have defined the following basic SQL MAP which has been shortened for brevity.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
        PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
        "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Application">
 
	<!-- applicationMap - Application Object Map  -->
	<resultMap id="applicationMap" class="com.example.model.Application" groupBy="id">
		<result property="appId" column="APP_ID" />
		<result property="name" column="NAME" />
		...
	</resultMap>
 
	<!-- list -->
	<select id="Application.list" resultMap="applicationMap" >
		...
	</select>
 
	<!-- insert -->
	<insert id="Application.insert" parameterClass="com.example.model.Application">
		...
	</insert>
 
	<!-- update -->
	<update id="Application.update" parameterClass="com.example.model.Application">
		...
	</update>
 
	<!-- delete -->
	<delete id="Application.delete" parameterClass="com.example.model.Application">
		...
	</delete>
 
</sqlMap>

In addition to created the SQLMap we’ve also create our basic DAO interface ApplicationDAO and implementation ApplicationDAOImpl which extends Spring’s SqlMapClientDaoSupport class.

package com.example.dao;
 
import java.util.List;
import com.example.model.Application;
 
public interface ApplicationDAO {
 
	List<Application> list();
 
	int update( Application obj );
 
	Integer insert( Application obj );
 
	int delete( Application obj );
 
}
package com.example.dao.impl;
 
import java.util.List;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
 
import com.example.dao.ApplicationDAO;
import com.example.model.Application;
 
public class ApplicationDAOImpl extends SqlMapClientDaoSupport implements ApplicationDAO {
 
	@SuppressWarnings("unchecked")
	public List<Application> list(){
		return (List<Application>) getSqlMapClientTemplate().queryForList( "Application.list" );
	}
 
	public Integer insert( Application obj ){
		Integer result = Integer.valueOf(-1);
		try {
			result = (Integer) getSqlMapClientTemplate().insert( "Application.insert", obj );
		} catch ( Exception e ) {
			log.error( "Failed to insert Application: " + e.getMessage() );
		}
		return result;
	}
 
	public int update( Application obj ){
		return getSqlMapClientTemplate().update( "Application.update", obj );
	}	
 
	public int delete( Application obj ){
		return getSqlMapClientTemplate().delete( "Application.delete", obj );
	}
 
}

Define the new processInBatch method

The processInBatch method will be responsible for setting up and executing the batch. It will take a list of Applications that are to be updated and perform the update SQL Map operation for each of them. To begin lets define the method stub in the ApplicationDAO interface and ApplicationDAOImpl class

// ApplicationDAO
int processInBatch( List<Application> applications );
// ApplicationDAOImpl
public int processInBatch( List<Application> applications ) {
 
}

Understanding the Batch Logic

To perform Batch Processing it is important to understand the two main classes that you will be interacting with SqlMapClientCallback and SqlMapExecutor

The SqlMapClientCallback class

The SqlMapClientCallback is a class to be overwritten in line that will perform the actual batch process. In it you define the doInSqlMapClient method. The SqlMapClientCallback object creates and passes the SqlMapExecutor instance to this method for your usage in setting up and executing the batch. The doInSqlMapClient method like the rest of the methods returns an Object so you can return any object you want.

try {
    Integer updateCount = (Integer) getSqlMapClientTemplate().execute( new SqlMapClientCallback() {
        public Object doInSqlMapClient( SqlMapExecutor executor ) throws SQLException {
 
        }
    });
    return updateCount.intVal();
catch (Exception e ) {
    return -1;
}

Looking at the above base implementation you can see that the general setup is the same for any batch processing you will need to perform the only difference is how you define the doInSqlMapClient method.

Implementing the doInSqlMapClient

The main batch worker is the SqlMapExecutor object. This object has 2 additional methods in addition to the basic insert, update, and execute: startBatch and executeBatch. The startBatch method is used to specify that you are performing the following statements as a batch, instead of executing them in line. Once you have set all your statements the executeBatch method is used to execute all of the statements in a batch and return the update count.

In our example as we are updating all the Applications passed to the processInBatch method we will start the batch, iterate over all applications, for each application call update on the executor for that object, then execute the batch.

executor.startBatch();
Iterator<Application> iter = applications.iterator();
while( iter.hasNext() ) {
    executor.update( "Application.update", iter.next() );
}
return new Integer( executor.executeBatch() );

The complete processInBatch method

public int processInBatch( List<Application> applications ) {
    try {
        Integer updateCount = (Integer) getSqlMapClientTemplate().execute( new SqlMapClientCallback() {
            public Object doInSqlMapClient( SqlMapExecutor executor ) throws SQLException {
                executor.startBatch();
                Iterator<Application> iter = applications.iterator();
                while( iter.hasNext() ) {
                    executor.update( "Application.update", iter.next() );
                }
                return new Integer( executor.executeBatch() );	
            }
        });
        return updateCount.intVal();
    catch (Exception e ) {
        return -1;
    }
}

Wrapping it all Up

There you have it we’ve created a method that executes multiple SQL statements as a batch. This reduces the overhead of performing multiple statements individually and can increase the performance of your applications especially as you get to large sets of statements. The greatest thing is that you don’t need to define any new sql statements and can use the ones you’ve already defined for doing single modifications.

, , , , , , , , ,

Until the release of WordPress 3.0 due out later in the year, creating a sub navigation is still a somewhat obscure and tricky task. To hopefully shed some light on how to create a Sub Navigation for your own needs I am going to walk-through how you can output a pages child or sub pages. In simple terms how to display a second level navigation in your sidebar.

How to get Sub Pages

In WordPress the easiest way to get the a page’s child pages is to use the get_pages function. This function allows you to specify that you want the children of a page by using the child_of and parent parameters. When called this function returns an array that you can utilize to iterate over and output the child pages.

$child_pages = get_pages('child_of='. $post->ID; . '&parent=' . $post->ID;);

The $post variable is used in WordPress templates to denote the current post or page. We utilize the ID property to specify we want returned all pages that are children of the current page.

How to output the pages in a list

To output a list of the sub pages we can iterate over the children and output the page titles and links in a list by using the get_page_link function and the ID and post_title properties of the returned Page object.

echo '<ul class="subNav">';
    foreach( $child_pages as $c_page ) {
    echo '<li><a href="' . get_page_link($c_page->ID) . '">' . $c_page->post_title . '</a></li>';
}
echo '</ul>';

The full example

Using the above code we will be executing the code on all website pages including posts and categories. To limit the execution to only pages we can utilize the is_page function. As we want to display the secondary navigation when we are on the parent page or child page we will need to check the current page to determine if we are on a root page or child page by using the post_parent property. Using this we can determine if we need to get the children of the current page or the children of the page’s parent. Doing so allows us to consistently output a Sub Page Navigation as can be seen here.

if( is_page() ) {
    $the_ID = $post->ID;
    $i_page = $post;
    if( $post->post_parent ) {
       $the_ID = $post->post_parent;
       $i_page = get_page($the_ID);
    }
 
    $child_pages = get_pages('child_of='. $the_ID . '&parent=' . $the_ID);
 
    if( count($child_pages) > 0 ) {
        echo '<li class="widget"><h2><a href="' . get_page_link($the_ID) . '">' . $i_page->post_title . '</a></h2><ul>';
        foreach( $child_pages as $c_page ) {
            echo '<li><a href="' . get_page_link($c_page->ID) . '">' . $c_page->post_title . '</a></li>';
        }
        echo '</ul></li>';
    }
}
, , , , ,

For some reason I have the utmost trouble remembering how to do a single line or inline if else statement. This article is mainly for myself so hopefully I will remember the next time I want to do an inline if else statement.

The usual format for performing an if else statement is:

if( $val1 > $val2 ) {
    // code executed if true
} else {
    // code executed if false
}

If you are trying to set a variable to a value depending on a condition then it is often the case that an inline if else statement will be sufficient and easier to read. This is done by the use of ?. The full format is (condition) ? (true output) : (false output) or as an example:

$val = ($var1 > $var2) ? $var1 : $var2;
, , , , ,

When developing a new system or software you will often find yourself unsure on the proper naming schema to utilize, or you may find out you need to comply with a company’s standard nomenclature. When this happens you may want to take note of the sp_rename stored procedure available in Sybase. This procedure allows you to rename a table, column, or index object be forewarned though that renaming a table can break stored procedures or queries that utilize the table and they will need to be updated appropriately.

Renaming a Database Table with sp_rename

To rename a table all you need to do is execute the procedure passing the name of the table to be modified and the new name for the table.

EXEC SP_RENAME MY_TABLE_OLD, MY_TABLE_NEW

Renaming a Table Column with sp_rename

To rename a column you need to specify the table and column in the first parameter and then in the 2nd parameter only put the new name of the column.

EXEC SP_RENAME MY_TABLE_NEW.old_id, new_id

Renaming a Table Index with sp_rename

To rename an index you need to specify the table and index in the first parameter and then in the 2nd parameter only put the new name of the index.

EXEC SP_RENAME MY_TABLE_NEW.id_idx, new_id_idx

It is important to note that if you have a column and index with the same name for a table you can specify a third parameter saying that you want to rename the index or column

EXEC SP_RENAME MY_TABLE_NEW.client_id, new_client_id, "index"

Resources

, , , ,

When writing a post to your WordPress powered blog or website have you ever wished you could split it up into multiple pages? The good news is that you can WordPress comes by default with the ability to create paginated posts by use of the Page-Link tag. This tag notifies WordPress that the following content should be on different page then the proceeding content.

The tag is used by simply inserting the text <!–nextpage–> into your post. There used to be a button to make this task easier on the user but it was removed to clean up the tools bar. You may find that this tag is not working for you in your site, the reason for this is that the theme you are using failed to implement the Page-Link function into their templates to display the pages. You can correct this by calling the wp_link_pages function in your single post template.

<?php wp_link_pages(); ?>

You can fully customize the page link by the usage of various parameters including before, after, next_or_number, and other self explanatory options. For a full list of options check out the Styling Page-Links page of the WordPress Codex.

, , , , , ,