<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>lstierneyltd &#187; Examples</title>
	<atom:link href="http://lstierneyltd.com/blog/category/development/examples/feed/" rel="self" type="application/rss+xml" />
	<link>http://lstierneyltd.com/blog</link>
	<description>Yet another development blog</description>
	<lastBuildDate>Wed, 13 Jul 2011 12:55:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>Java to XML, XML to Java (Marshalling and Unmarshalling)</title>
		<link>http://lstierneyltd.com/blog/development/examples/java-to-xml-xml-to-java-marshalling-and-unmarshalling/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/java-to-xml-xml-to-java-marshalling-and-unmarshalling/#comments</comments>
		<pubDate>Wed, 13 Jul 2011 12:55:13 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jaxb]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=273</guid>
		<description><![CDATA[Introduction JDK6 and JAXB2.x (which comes with JDK6) make marshalling Java to XML and unmarshalling XML to Java a snap, almost trivial. Example Java to XML XML to Java product.java Note: the @XmlRootElement is vital here! product.xml]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>JDK6 and JAXB2.x (which comes with JDK6) make marshalling Java to XML and unmarshalling XML to Java a snap, almost trivial.</p>
<h3>Example</h3>
<h4>Java to XML</h4>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class JavaToXML {
	public static void main(String[] args) throws Exception {
		JAXBContext context = JAXBContext.newInstance(Product.class);

		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

		Product object = new Product();
		object.setCode(&quot;WI1&quot;);
		object.setName(&quot;Widget Number One&quot;);
		object.setPrice(BigDecimal.valueOf(300.00));

		m.marshal(object, System.out);
	}
}
</pre>
<h4>XML to Java</h4>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XMLToJava {

	public static void main(String[] args) {
		try {
			JAXBContext jc = JAXBContext.newInstance(Product.class);
			Unmarshaller u = jc.createUnmarshaller();

			File f = new File(&quot;product.xml&quot;);
			Product product = (Product) u.unmarshal(f);

			System.out.println(product.getCode());
			System.out.println(product.getName());
			System.out.println(product.getPrice());
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}
</pre>
<h4>product.java</h4>
<p>Note: the @XmlRootElement is vital here!</p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Product {
	private String code;
	private String name;
	private BigDecimal price;

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public BigDecimal getPrice() {
		return price;
	}
	public void setPrice(BigDecimal price) {
		this.price = price;
	}
}
</pre>
<h4>product.xml</h4>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;product&gt;
    &lt;code&gt;WI1&lt;/code&gt;
    &lt;name&gt;Widget Number One&lt;/name&gt;
    &lt;price&gt;300.0&lt;/price&gt;
&lt;/product&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/java-to-xml-xml-to-java-marshalling-and-unmarshalling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Validation in Annotation Based Validating Spring Beans</title>
		<link>http://lstierneyltd.com/blog/development/examples/spring-examples/unit-testing-validation-in-annotation-based-validating-spring-beans/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/spring-examples/unit-testing-validation-in-annotation-based-validating-spring-beans/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 08:57:07 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=245</guid>
		<description><![CDATA[Motivation I added validation, via annotations, to a Spring &#8220;Model&#8221; bean. I needed someway to Unit Test this validation, without running the container and without initialising the Spring context. The bean (simplified) The Unit Test More It actually took me a few hours to work the above test out (simple as it is). If I [...]]]></description>
			<content:encoded><![CDATA[<h3>Motivation</h3>
<p>I added validation, via annotations, to a Spring &#8220;Model&#8221; bean. I needed someway to Unit Test this validation, <em>without</em> running the container and <em>without</em> initialising the Spring context.</p>
<h3>The bean (simplified)</h3>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public final class ProductModel {

    @NotNull
    @Size(max=100)
    @Pattern(regexp=&quot;[^\n^\t^\r]+&quot;, message=&quot;Long Name must not contain New Lines, Carriage Returns or Tabs&quot;)
    private String longName;

    @Size(max=20)
    private String shortName;

    // rest snipped for brevity
}
</pre>
<h3>The Unit Test</h3>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import java.util.Set;

import javax.validation.ConstraintViolation;

import junit.framework.Assert;

import org.hibernate.validator.HibernateValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

public class Temp {
    private LocalValidatorFactoryBean localValidatorFactory;

    @Before
    public void setup() {
        localValidatorFactory = new LocalValidatorFactoryBean();
        localValidatorFactory.setProviderClass(HibernateValidator.class);
        localValidatorFactory.afterPropertiesSet();
    }
    @Test
    public void testLongNameWithInvalidCharCausesValidationError() {
        final ProductModel productModel = new ProductModel();
        productModel.setLongName(&quot;A long name with\t a Tab character&quot;);
    	Set&lt;ConstraintViolation&lt;ProductModel&gt;&gt; constraintViolations = localValidatorFactory.validate(productModel);
    	Assert.assertTrue(&quot;Expected validation error not found&quot;, constraintViolations.size() == 1);
    }
}
</pre>
<h3>More</h3>
<p>It actually took me a few hours to work the above test out (simple as it is). If I hadn&#8217;t stumbled upon <a href="https://src.springsource.org/svn/spring-framework/trunk/org.springframework.context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java">these Spring Unit Tests</a>, I might never have got it.</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/spring-examples/unit-testing-validation-in-annotation-based-validating-spring-beans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring MVC URI Template Example</title>
		<link>http://lstierneyltd.com/blog/development/examples/spring-examples/spring-mvc-uri-template-example/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/spring-examples/spring-mvc-uri-template-example/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 14:04:25 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=241</guid>
		<description><![CDATA[Background So, I&#8217;m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration. As I was trawling through the source code I noticed &#8220;some wierd&#8221; syntax: &#8220;/{xxxx}&#8221; (which of course I had to look up!). Most of the following is based upon the excellent Spring Documentation. [...]]]></description>
			<content:encoded><![CDATA[<h3>Background</h3>
<p>So, I&#8217;m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration. As I was trawling through the source code I noticed &#8220;some wierd&#8221; syntax: &#8220;/{xxxx}&#8221; (which of course I had to look up!).</p>
<p>Most of the following is based upon the excellent <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib" target="_blank">Spring Documentation</a>. I&#8217;ve lifted and rewritten the parts I require to serve as a condensed &#8220;aide-mémoire&#8221;.</p>
<h3>Description</h3>
<p>A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI.<br />
<code><span id="more-241"></span></code><br />
For example, the URI Template</p>
<pre>http://foo.bar.com/products/{productName}</pre>
<p>contains the variable &#8220;productName&#8221;. If we assign the variable the value &#8220;widgetA&#8221;, the URI Template yields:</p>
<pre>http://foo.bar.com/products/widgetA</pre>
<h3>Example</h3>
<pre class="brush: java; title: ; notranslate">
@Controller
public class ProductController {
    @RequestMapping(value=&quot;/products/{productName}, method = RequestMethod.GET)
    public String getProductDetails(@PathVariable(&quot;productName&quot;) String productName, Model model) {
        Product product = this.productService.getProduct(productName);
        model.addAttribute(&quot;productDetails&quot;, product);
        return &quot;productDetailPage&quot;;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/spring-examples/spring-mvc-uri-template-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring MVC 3 @ModelAttribute Annotation Example</title>
		<link>http://lstierneyltd.com/blog/development/examples/spring-examples/spring-mvc-3-modelattribute-annotation-example/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/spring-examples/spring-mvc-3-modelattribute-annotation-example/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 10:53:01 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=236</guid>
		<description><![CDATA[Background So, I&#8217;m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration files. As I was trawling through the source code I noticed the &#8220;@ModelAttribute&#8221; annotation (which of course I had to look up!). If the above background seems familiar that&#8217;s because it&#8217;s the same [...]]]></description>
			<content:encoded><![CDATA[<h3>Background</h3>
<p>So, I&#8217;m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration files. As I was trawling through the source code I noticed the &#8220;@ModelAttribute&#8221; annotation (which of course I had to look up!).</p>
<p>If the above background seems familiar that&#8217;s because it&#8217;s the same as for a previous Spring Annotation post I made (ed: this is in danger of turning into a mini-series)</p>
<h3>Description</h3>
<p>Most of the following is based upon the excellent <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib" target="_blank">Spring Documentation</a>. I&#8217;ve simply lifted and rewritten the parts I require to serve as an &#8220;aide-mémoire&#8221;.</p>
<p>The @ModelAttribute annotation serves two purposes depending on how it is used:</p>
<p><code><span id="more-236"></span></code></p>
<h4>At Method level</h4>
<p>Use @ModelAttribute at the method level to <em>provide reference data for the model</em>. @ModelAttribute annotated methods are executed before the chosen @RequestMapping annotated handler method. They effectively pre-populate the implicit model with specific attributes, often loaded from a database. Such an attribute can then already be accessed through @ModelAttribute annotated handler method parameters in the chosen handler method, potentially with binding and validation applied to it.</p>
<p>In other words; a method annotated with @ModelAttribute will populate the specified &#8220;key&#8221; in the model. This happens BEFORE the @RequestMapping</p>
<h4>At Method Parameter level</h4>
<p>When you place @ModelAttribute on a method parameter, @ModelAttribute maps a model attribute to the specific, annotated method parameter. This is how the controller gets a reference to the object holding the data entered in the form.</p>
<h3>Examples</h3>
<h4>Method Level</h4>
<pre class="brush: java; title: ; notranslate">
@Controller
public class MyController {
    @ModelAttribute(&quot;productsList&quot;)
    public Collection&lt;Product&gt; populateProducts() {
        return this.productsService.getProducts();
    }
    // @RequestMapping etc omitted for brevity
}
</pre>
<p>So, in the above example, &#8220;productsList&#8221; in the Model is populated before the the @RequestMapping is performed.</p>
<h4>Method parameter level</h4>
<pre class="brush: java; title: ; notranslate">
@Controller
public class MyController {
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute(&quot;product&quot;) Product myProduct, BindingResult result, SessionStatus status) {

        new ProductValidator().validate(myProduct, result);
        if (result.hasErrors()) {
            return &quot;productForm&quot;;
        }
        else {
            this.productsService.saveProduct(myProduct);
            status.setComplete();
            return &quot;productSaved&quot;;
        }
    }
}
</pre>
<p>In the above example &#8220;myProduct&#8221; is populated with the corresponding value from the Model.</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/spring-examples/spring-mvc-3-modelattribute-annotation-example/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Spring MVC 3.x @PathVariable Annotation Example</title>
		<link>http://lstierneyltd.com/blog/development/spring-mvc-3-x-pathvariable-annotation-example/</link>
		<comments>http://lstierneyltd.com/blog/development/spring-mvc-3-x-pathvariable-annotation-example/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 13:41:09 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Examples]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=228</guid>
		<description><![CDATA[Background So, I&#8217;m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration files. As I was trawling through the source code I noticed the &#8220;@PathVariable&#8221; annotation (which of course I had to look up!). Example Imagine you&#8217;d like to create a controller that would allow [...]]]></description>
			<content:encoded><![CDATA[<h3>Background</h3>
<p>So, I&#8217;m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration files. As I was trawling through the source code I noticed the &#8220;@PathVariable&#8221; annotation (which of course I had to look up!).</p>
<h3>Example</h3>
<p>Imagine you&#8217;d like to create a controller that would allow users to see view products by using a URL such as http://foo.bar.com/productDetails/someProduct</p>
<pre>
e.g.

http://foo.bar.com/productDetails/widgetA - display details for widgetA
http://foo.bar.com/productDetails/widgetB - display details for widgetB
</pre>
<p>The @PathVariable annotation makes this easy&#8230;</p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

@Controller
public class ShowProductController {

    @RequestMapping(&quot;/productDetails/{productName}&quot;) // Handle any request of the form &quot;/productDetails/XXXXX&quot;
    public String showProduct(Model model, @PathVariable(&quot;productName&quot;) String productName) {
        model.addAttribute(&quot;productName&quot;, productName);
        return &quot;showProduct&quot;; // viewname
    }
}
</pre>
<h3>What just happened?</h3>
<p>Note the {productName} in the @RequestMapping &#8211; this is the path variable. The @PathVariable annotation on the next line captures the value and binds it to the method argument</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/spring-mvc-3-x-pathvariable-annotation-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EasyMock Capture Example</title>
		<link>http://lstierneyltd.com/blog/development/easymock-capture-example/</link>
		<comments>http://lstierneyltd.com/blog/development/easymock-capture-example/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 09:46:50 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Examples]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=184</guid>
		<description><![CDATA[Background EasyMock version 2.4 introduced some new functionality &#8211; the ability to capture the arguments passed to mock objects. As ever a few lines of code speaks volumes. Capture Example Test Class Source code for classes under test after the break&#8230;&#8230;. Service Interface Service Implementation Dao Interface Dao Implementation Domain Object (Bean)]]></description>
			<content:encoded><![CDATA[<h4>Background</h4>
<p>EasyMock version 2.4 introduced some new functionality &#8211; the ability to <em>capture</em> the arguments passed to mock objects. As ever a few lines of code speaks volumes.</p>
<h4>Capture Example</h4>
<p><strong>Test Class</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import static org.junit.Assert.assertEquals;

import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Before;
import org.junit.Test;

public class TestServiceImpl {
    private Service service;
    private Dao dao;
    private IMocksControl controller;
    private final String description = &quot;description&quot;;

    @Before
    public void setUp() throws Exception {
        controller = EasyMock.createStrictControl();
        dao = controller.createMock(Dao.class);
        service = new ServiceImpl();
        service.setDao(dao);
    }
    @Test
    public void testSave() {
        Capture &lt;DomainObject&gt; capturedArgument = new Capture &lt;DomainObject&gt;();
        dao.save(EasyMock.and(EasyMock.capture(capturedArgument), EasyMock.isA(DomainObject.class)));
        controller.replay();
        service.save(description);
        controller.verify();
        DomainObject record = capturedArgument.getValue();
        assertEquals(description, record.getDescription());
        assertEquals(&quot;getNextId&quot;, record.getId());
    }
}
</pre>
<p>Source code for classes under test after the break&#8230;&#8230;.<br />
<code><span id="more-184"></span></code><br />
<strong>Service Interface</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public interface Service {
    void save(String description);
    void setDao(Dao dao);
}
</pre>
<p><strong>Service Implementation</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public class ServiceImpl implements Service {
    private Dao dao;

    public void save(String description) {
        DomainObject record = new DomainObject();
        record.setDescription(description);
        record.setId(&quot;getNextId&quot;);
        dao.save(record);
    }
    public void setDao(Dao dao) {
        this.dao = dao;
    }
}
</pre>
<p><strong>Dao Interface</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public interface Dao {
    public abstract void save(DomainObject record);
}
</pre>
<p><strong>Dao Implementation</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public class DaoImpl implements Dao {
    public void save(DomainObject record) {
        // do something
    }
}
</pre>
<p><strong>Domain Object (Bean)</strong></p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

public class DomainObject {
    private String id;
    private String description;
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/easymock-capture-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Ibatis Typehandlers to fix Oracle Date &#8220;missing time&#8221;</title>
		<link>http://lstierneyltd.com/blog/development/examples/using-ibatis-typehandlers-to-fix-oracle-date-missing-time/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/using-ibatis-typehandlers-to-fix-oracle-date-missing-time/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 11:25:44 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[ibatis]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[oracle]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=160</guid>
		<description><![CDATA[The Problem When using Ibatis to retrieve Date type values, on Oracle 10g (some driver versions), the time portion of the value returned from the database is not mapped onto the Java object. i.e. In DB: 02-JAN-10 13:30:00 In Java Object after mapping: 02-JAN-10 00:00:00 The Ibatis ResultMapper, snippet, looks like this: .... &#60;result property="savedDate" [...]]]></description>
			<content:encoded><![CDATA[<h4>The Problem</h4>
<p>When using Ibatis to retrieve Date type values, on Oracle 10g (some driver versions), the time portion of the value returned from the database is not mapped onto the Java object.</p>
<p>i.e.</p>
<p>In DB: <strong>02-JAN-10 13:30:00</strong><br />
In Java Object after mapping: <strong>02-JAN-10 00:00:00</strong></p>
<p>The Ibatis ResultMapper, snippet, looks like this:</p>
<pre>
....
&lt;result property="savedDate" column="SAVED_DATE" javaType="java.util.Date" jdbcType="DATE"/&gt;
....
</pre>
<p><code><span id="more-160"></span></code></p>
<h4>The Solution</h4>
<p>1. Implement our old friend the Ibatis TypeHandlerCallback.</p>
<pre class="brush: plain; title: ; notranslate">
package foo.bar;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

public class CustomDateHandler implements TypeHandlerCallback {

    public Object getResult(ResultGetter getter) throws SQLException {
        final Object obj = getter.getTimestamp();
        return obj != null ? (Date) obj : null;
    }

    public void setParameter(ParameterSetter setter,Object value) throws SQLException {
        setter.setTimestamp(value != null ? new Timestamp(((Date)value).getTime()) : null);
    }

    public Object valueOf(String datetime) {
        return Timestamp.valueOf(datetime);
    }
}
</pre>
<p>2. Add Typehandlers and TypeAliases to Ibatis config</p>
<pre>
&lt;typeAlias alias="OracleDateHandler" type="foo.bar.CustomDateHandler"/&gt;
&lt;typeHandler callback="OracleDateHandler" jdbcType="DATETIME" javaType="date"/&gt;
</pre>
<p>3. Update resultMap to use new &#8220;type&#8221;</p>
<pre>
....
&lt;result property="savedDate" column="SAVED_DATE" javaType="java.util.Date" jdbcType="DATETIME"/&gt;
....
</pre>
<h4>Important Note!</h4>
<p>This solution deals with issues caused by certain versions of the Oracle JDBC drivers. I believe that the 11g drivers fix this issue. As ever YMMV&#8230;..</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/using-ibatis-typehandlers-to-fix-oracle-date-missing-time/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unit Testing Spring apps with @RunWith(SpringJUnit4ClassRunner.class)</title>
		<link>http://lstierneyltd.com/blog/development/examples/unit-testing-spring-apps-with-runwithspringjunit4classrunner-class/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/unit-testing-spring-apps-with-runwithspringjunit4classrunner-class/#comments</comments>
		<pubDate>Thu, 24 Jun 2010 11:13:15 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=153</guid>
		<description><![CDATA[The Problem I love Spring, who doesn&#8217;t? One thing however that I found, until recently, a bit awkward was Unit Testing objects which were constructed and initiated via the Spring context and injected into other objects that consumed them. I have seen and used many and varied &#8220;bespoke&#8221; ways to do this, none of which [...]]]></description>
			<content:encoded><![CDATA[<h4>The Problem</h4>
<p>I love <a href="http://www.springsource.org/" target="_blank">Spring</a>, who doesn&#8217;t?</p>
<p>One thing however that I found, until recently, a bit awkward was Unit Testing objects which were constructed and initiated via the Spring context and injected into other objects that consumed them. I have seen and used many and varied &#8220;bespoke&#8221; ways to do this, none of which I found satisfying.</p>
<p>This was until a <a href="http://andrew.montheheids.com" target="_blank">collegue</a> introduced me to the wonder that is <a href="http://static.springsource.org/spring/docs/2.5.x/reference/testing.html" target="_blank">SpringJUnit4ClassRunner</a>. I know, I know, I should have been aware of this ages ago but as they say on millionaire &#8220;it&#8217;s easy if you know the answer&#8221;!<br />
<code><span id="more-153"></span></code></p>
<h4>Solution</h4>
<p>A few lines of code speaks more than a thousand words from me&#8230;&#8230;</p>
<pre class="brush: java; title: ; notranslate">
package foo.bar;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={&quot;daos.xml&quot;})
public final class DaoTests {

    @Autowired
    private MyDao dao;

    @Test
    public void testLoadTitle() throws Exception {
        String result = dao.doSomething();
        assertNotNull(result);
    }
}
</pre>
<h4>Whats going on?</h4>
<p><strong><em>@RunWith(SpringJUnit4ClassRunner.class)</em></strong><br />
Quoting the docs: &#8220;SpringJUnit4ClassRunner is a custom extension of JUnit4ClassRunner which provides functionality of the Spring TestContext Framework to standard JUnit 4.4+ tests by means of the TestContextManager and associated support classes and annotations.&#8221;</p>
<p>Basically this means that tests are going to be able to get hold of instantiated beans as defined in the Spring context files (see below).</p>
<p><strong><em>@ContextConfiguration(locations={&#8220;daos.xml&#8221;})</em></strong><br />
This is telling the test where to get the context files containing the bean definitions. Note that if you do not provide any arguments to the annotation then a default will be looked for.</p>
<p>For example: If your class is named foo.bar.DaoTests, the context loader will attempt to load your application context from &#8220;classpath:/foo/bar/DaoTests-context.xml&#8221;.</p>
<p><strong><em>@Autowired</em></strong><br />
This will autowire BY TYPE, beans found in the context. Alternatively you could use @Resource to inject the dependencies by NAME (useful if several beans are of the same type)</p>
<h4>Conclusion</h4>
<p>Now it&#8217;s simply the case of adding a few annotations and a few imports to be able easily write tests which use Spring beans. All in all, a very unobtrusive (and fast) process.</p>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/unit-testing-spring-apps-with-runwithspringjunit4classrunner-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ibatis TypeHandlerCallback Enum Example</title>
		<link>http://lstierneyltd.com/blog/development/examples/ibatis-typehandlercallback-enum-example/</link>
		<comments>http://lstierneyltd.com/blog/development/examples/ibatis-typehandlercallback-enum-example/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 11:29:53 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[ibatis]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=147</guid>
		<description><![CDATA[Problem You need Ibatis to perform custom processing before parameters are set on a Prepared Statement or after the results are retrieved from the result set. Maybe to convert Y/N to boolean, map results to custom objects etc Solution You probably want to look at implementing Ibatis&#8217; TypeHandlerCallBack, the API docs for which are here [...]]]></description>
			<content:encoded><![CDATA[<h4>Problem</h4>
<p>You need Ibatis to perform custom processing before parameters are set on a Prepared Statement or after the results are retrieved from the result set. Maybe to convert Y/N to boolean, map results to custom objects etc</p>
<h4>Solution</h4>
<p>You probably want to look at implementing Ibatis&#8217; TypeHandlerCallBack, the API docs for which are <a target="_blank" href="http://ibatis.apache.org/docs/java/user/com/ibatis/sqlmap/client/extensions/TypeHandlerCallback.html">here</a><br />
<code><span id="more-147"></span></code></p>
<h4>Example</h4>
<p>In this example I map a &#8220;prev&#8221; or &#8220;next&#8221; coming back from the DB (as &#8220;direction&#8221;) to the Enum described in <a href="http://lstierneyltd.com/blog/development/java-5-enum-example/" target="_blank" >this post</a>.</p>
<h4>Ibatis Config</h4>
<pre class="brush: plain; title: ; notranslate">
&lt;parameterMap id=&quot;findByCompanyIdParams&quot; class=&quot;map&quot;&gt;
    &lt;parameter mode=&quot;IN&quot; property=&quot;companyId&quot; javaType=&quot;java.lang.String&quot; jdbcType=&quot;VARCHAR&quot;/&gt;
    &lt;parameter mode=&quot;IN&quot; property=&quot;nextKeyId&quot; javaType=&quot;java.lang.String&quot; jdbcType=&quot;VARCHAR&quot;/&gt;
    &lt;parameter mode=&quot;IN&quot; property=&quot;maxOccurs&quot; javaType=&quot;java.lang.Integer&quot; jdbcType=&quot;NUMBER&quot;/&gt;
    &lt;parameter mode=&quot;IN&quot; property=&quot;direction&quot; javaType=&quot;OBJECT&quot;
        typeHandler=&quot;foo.bar.PagingCriteriaDirectionTypeHandlerCallback&quot; jdbcType=&quot;VARCHAR&quot;/&gt;
    &lt;parameter mode=&quot;OUT&quot; property=&quot;outCursor&quot; jdbcType=&quot;ORACLECURSOR&quot; javaType=&quot;java.sql.ResultSet&quot;/&gt;
&lt;/parameterMap&gt;
</pre>
<h4>Java code</h4>
<pre class="brush: plain; title: ; notranslate">
package foo.bar;

import java.sql.SQLException;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;
import foo.bar.MyRuntimeException;

public class PagingCriteriaDirectionTypeHandlerCallback implements TypeHandlerCallback{

	public Object getResult(ResultGetter getter) throws SQLException {
		String s = getter.getString();
		if (PagingCriteriaDirection.NEXT.getDescription().equalsIgnoreCase(s)) {
			return PagingCriteriaDirection.NEXT;
		} else if (PagingCriteriaDirection.PREV.getDescription().equalsIgnoreCase(s)) {
			return PagingCriteriaDirection.PREV;
		} else {
			throw new SQLException(&quot;Unexpected value &quot; + s + &quot; found where &quot;
					+ PagingCriteriaDirection.PREV.getDescription() + &quot; or &quot; + PagingCriteriaDirection.NEXT.getDescription() + &quot; was expected.&quot;);
		}
	}

	public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
		PagingCriteriaDirection direction = (PagingCriteriaDirection) parameter;

		if (direction.equals(PagingCriteriaDirection.NEXT)) {
			setter.setString(PagingCriteriaDirection.NEXT.getDescription());
		}
		else {
			setter.setString(PagingCriteriaDirection.PREV.getDescription());
		}
	}

	public Object valueOf(String s) {
	    if (PagingCriteriaDirection.NEXT.getDescription().equalsIgnoreCase(s)) {
	        return PagingCriteriaDirection.NEXT;
	    }
	    else if (PagingCriteriaDirection.PREV.getDescription().equalsIgnoreCase(s)) {
	        return PagingCriteriaDirection.PREV;
	    }
	    else {
	    	throw new MyRuntimeException(&quot;Unexpected value &quot; + s + &quot; found where &quot;
					+ PagingCriteriaDirection.PREV.getDescription() + &quot; or &quot; + PagingCriteriaDirection.NEXT.getDescription() + &quot; was expected.&quot;);
	    }
	}

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/examples/ibatis-typehandlercallback-enum-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java 5 Enum Example</title>
		<link>http://lstierneyltd.com/blog/development/java-5-enum-example/</link>
		<comments>http://lstierneyltd.com/blog/development/java-5-enum-example/#comments</comments>
		<pubDate>Thu, 10 Jun 2010 10:00:49 +0000</pubDate>
		<dc:creator>lawrence</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Examples]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://lstierneyltd.com/blog/?p=142</guid>
		<description><![CDATA[Description This simple example of a Java 5 Enum models a PREV/NEXT you might commonly see in a web app.]]></description>
			<content:encoded><![CDATA[<h4>Description</h4>
<p>This simple example of a Java 5 Enum models a PREV/NEXT you might commonly see in a web app.</p>
<pre class="brush: plain; title: ; notranslate">
package foo.bar;

public enum PagingCriteriaDirection {
    NEXT(&quot;Next&quot;), PREV(&quot;Previous&quot;);

    private String description;

    private PagingCriteriaDirection(String desc){
        description = desc;
    }

    public String getDescription() {
    	return description;
    }

    @Override
    public String toString() {
    	return description;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://lstierneyltd.com/blog/development/java-5-enum-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

