October 30, 2015 at 2:26 pm | Posted in Uncategorized | Leave a comment

Please follow my new blog here:


Use jobParameters value in HibernateCursorItemReader HQL

October 8, 2010 at 5:03 pm | Posted in Uncategorized | 4 Comments
Tags: , ,

When ItemReader, ItemWriter, or ItemProcessor need to use JobParameters, you can set their bean scope to “step” and able to reference parameters.

  • doesn’t need to use spring3
  • bean needs to be a “step” scope.
  • expressions are  “#{}” or “%{}”.
    impl is : org.springframework.batch.core.scope.StepScope.ExpressionHider

Here, I pass “from_date” as jobParameter, and bind it to the item reader HQL of HibernateCursorItemReader.

  <bean id="hibernateReader"
    <property name="sessionFactory" ref="sessionFactory"/>
    <property name="queryString">
          <![CDATA[ from Something where start_date <= :reqFromDate ]]>
    <property name="parameterValues">
        <entry key="reqFromDate" value="#{jobParameters['from_date']}"/>

OpenSessionInViewFilter v.s. OpenSessionInViewInterceptor

July 31, 2008 at 7:24 am | Posted in Uncategorized | 2 Comments
Tags: ,

Spring provides two implementation to achieve open session in view pattern.


Both of them will keep hibernate session open until view is rendered. However, even though both provides same function, they are implemented on fundamentally different techniques.


  • use Spring MVC function
  • small granularity to apply
  • configure in applicationContext.xml, [servlet_name]-servlet.xml, or spring config file.

* use DispatcherServlet (Spring MVC) interceptor function to keep opening hibernate session.

* If you only need to open hibernate session for specific controllers, interceptor is a best choice because it can be configured to each controller(actually, handler mapping level).

e.g.) one controller uses hibernate, but another controller uses different technology.


  • use ServletFilter function
  • large granularity to apply
  • configure in web.xml
  • Spring MVC is not required.

* servlet specification

Expose Java5 Enum to JSP(JSTL)

July 28, 2008 at 8:46 pm | Posted in Uncategorized | Leave a comment

Currently, Enum cannot be directly referenced in JSTL

We cannot do these:

  • ${ my.package.Enum }
  • ${ someEnum == MyEnum }

So, in order to access enums easily, Enums need to be in HttpServletRequest (request scope) or ServletContext(application scope).

  1. Store in ServletContext (Application scope)
  2. Store in HttpServletRequest (request scope, request.setAttribute())
    • ServletFilter (servlet)
    • HandlerInterceptor (spring)
    • Controller (spring, web-layer-action)

Sample Enum Class

public enum Language {

    private String name;

    Language(String name) { = name;

    public String getName() {
        return name;


public class EnumExposureHandlerInterceptor extends HandlerInterceptorAdapter {

    private Set<Class<? extends Enum>> enumClasses = new HashSet<Class<? extends Enum>>();

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        for (Class<? extends Enum> enumClass : enumClasses) {
            final String enumClassName = enumClass.getSimpleName();  // class of enum : Language
            final Enum[] enums = enumClass.getEnumConstants();  // enum instances : EN, JP,...

            // put them into map, so that we can access like this : Language.EN, Language.JP ...
            Map<String, Enum> map = new HashMap<String, Enum>(enums.length);
            for (Enum anEnum : enums) {
                map.put(, anEnum);

            // seting to scope
            request.setAttribute(enumClassName, map);


    public void setEnumClasses(Set<Class<? extends Enum>> enumClasses) {
        this.enumClasses = enumClasses;

Spring Configuration

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap" ref="urlMap"/>
<property name="interceptors">
            <bean class="mypackage.EnumExposureHandlerInterceptor">
<property name="enumClasses">

JdbcTemplate details part3

May 12, 2008 at 7:52 pm | Posted in Uncategorized | Leave a comment
Tags: ,

Error translation

Translate java.sql.SqlException to Spring’s data access exception hierarchy.

Root cause for all dao access exceptions. unchecked exception.
direct parent class is NestedRuntimeException

Native jdbc resource

When you need to work on native jdbc connections instead of spring wrapped connections, providing NativeJdbcExtractor to jdbcTemplate allows you to retrieve native connections. Then, you can cast the connection to the vendor specific connection object.

SingleConnectionDataSource, DriverManagerDataSource

Datasource for testing.

Create new connection every time.
useful for test outside of container, based on what API says.

Sub class of DriverManagerDataSource.
Always use the same connection, and not for multi threaded environement.

Transaction Management in JDBC

Utility class to retrieve a connection from spring transaction managers(thread bounded connection).

Let your datasource participate spring transaction management. reference my other post.

Implementation of PlatformTransactionManager. So, use this as a transaction manager if application solely use datasource. Bind connection to current thread.

JdbcTemplate details part2

May 9, 2008 at 7:46 am | Posted in Uncategorized | Leave a comment
Tags: ,

Package Hierarchy

Batch update

implement BatchPreparedStatementSetter or InterruptibleBatchPreparedStatement interfaces

For SimpleJdbcTemplate
you can also use value maps, bean property based objects, or SqlParameterSources
see SqlParameterSourceUtils

represente batch update sql as a java class.

SimpleJdbc classes

simplified jdbc operation classes using database metadata(retrieved from JDBC driver).

enhanced jdbcTemplate with java5 functions.

by giving table name(withTableName()), column names, and values, you can execute insert operation.

simple execution for stored procedure. in/out parameters can be given as Map, or SqlParmaeterSource.

JDBC Operations

considering each DB operation as object

abstract class that encapsulate all sql operations. This class defines a lot of execution methods. When you implement this class, need to provide rowMapper.

represent update operation as an object.
StoredProcedure: abstract class that you can extend for your stored procedure.

expect single result

JdbcTemplate details part1

May 5, 2008 at 7:41 pm | Posted in Uncategorized | Leave a comment
Tags: ,

JdbcTemplate methods

Data Retrieval

queryForInt(), queryForLong()
expects unique value.

expects one row. each column is a map key.

expects multiple rows. each entry of list is a map, and the map uses columns as keys.

expects one row as an instance

expects multiple rows. returns multiple objects. each row becomes one instance.


* PreparedStatementCreator
create prepared statement and bind values

* PreparedStatementSetter
bind values to prepared statement when you want to separate creation of prepared statement binding of values.

* ResultSetExtractor
process entire resultset and return one object. recommended to access resultset stateless

* RowCallbackHandler
process entire resultset statefull. Object which implement this interface will usually used after jdbctemplate call.

* RowMapper
process each result row and construct an object.

Data Manipulation

for insert,update, and delete statement


for DDL

JdbcTemplate extensions

* NamedParameterJdbcTemplate
Support named parameter (‘:id’,’:name’), use SqlParameterSource or Map to bind values to named parameters.

* SqlParameterSource
interface that represents keys, values, and sqlTypes for named parameters.

* SimpleJdbcTemplate
use Java5 functions such as vargs and generic.

Transaction aware datasource (use dbunit & hibernate in spring)

April 27, 2008 at 5:03 pm | Posted in Uncategorized | 4 Comments
Tags: , ,


use dbunit & hibernate in unit test

  • prepare test data with dbunit using datasource
  • test a dao method with hibernate
  • rollback all data (each testcase doesn’t pollute data)


preparing test data and running a test method must be executed under the same transaction in order to rollback.
=> dbunit(datasource) needs to participate spring transaction management.


use TransactionAwareDatasourceProxy

[How it works]

Transaction manager acquires a DB connection and put it to connection holder in thread local.
Whenever getConnection() is called, same connection will be retrieved from connection holder.
When close() is called, it doesn’t close connection.
At the end of transaction, finally connection will be closed.

When transaction manager begins transaction, ConnectionHolder instance will be created and hold actual connection.
When transaction is done, connection will be closed.

wrap original datasource.
implementing DataSource interface
participate spring managed transaction control

proxy of Connection class
private inner class
delegate standard Connection methods(equals, close, …) to DataSourceUtils

[Sample Config]

 | Datasource with Transaction support.

<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
     <constructor-arg ref="dbcpDataSource"/>

<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
     <property name="driverClassName" value="${hibernate.connection.driver_class}"/>
     <property name="url" value="${hibernate.connection.url}"/>
     <property name="username" value="${hibernate.connection.username}"/>
     <property name="password" value="${hibernate.connection.password}"/>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
    <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
    <property name="hibernateProperties" ref="hibernateProperties"/>
    <!--<property name="useTransactionAwareDataSource" value="true"/>-->

[Sample Test Code]

final IDatabaseConnection dbUnitConnection = new DatabaseConnection(this.getDataSource());

// Do some operations with dbunit
// eg)
// DatabaseOperation.DELETE.execute(connection, dataSet);

// this doesn't close connection since method is executed under transaction
DataSourceUtils.releaseConnection(dbUnitConnection.getConnection(), this.getDataSource());

[Key Spring Classes]

Hello world!

March 2, 2008 at 4:56 am | Posted in Uncategorized | 1 Comment

Welcome to This is your first post. Edit or delete it and start blogging!

Create a free website or blog at
Entries and comments feeds.