<?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>Source Allies Blog</title>
	<atom:link href="http://blogs.sourceallies.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.sourceallies.com</link>
	<description>Technical and process thinking from Source Allies employees</description>
	<lastBuildDate>Fri, 03 Feb 2012 17:45:38 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Hibernate Date vs Timestamp</title>
		<link>http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/</link>
		<comments>http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 20:24:21 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[timestamp]]></category>
		<category><![CDATA[UserType]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2559</guid>
		<description><![CDATA[I encountered a subtle hibernate mapping issue involving Dates and Timestamps.  The following test recreates this issue.


package com.sourceallies.logging;
&#160;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
&#160;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
&#160;
import javax.annotation.Resource;
&#160;
import org.apache.commons.lang.time.DateUtils;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
&#160;
import com.sourceallies.Person;
&#160;
@RunWith&#40;SpringJUnit4ClassRunner.class&#41;
@ContextConfiguration
@TransactionConfiguration&#40;defaultRollback=false&#41;
public class HibernateDateTimeTest &#123;
&#160;
	@Resource
	private SessionFactory sessionFactory;
&#160;
	private Session currentSession;
&#160;
	private Date birthDateWithTime;
	private Date birthDateWithoutTime;
	private Date createDate;
	private [...]]]></description>
			<content:encoded><![CDATA[<p>I encountered a subtle hibernate mapping issue involving <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Date.html">Dates</a> and <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html">Timestamps</a>.  The following test recreates this issue.<br />
<span id="more-2559"></span></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.logging</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> org.<span style="color: #006633;">junit</span>.<span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006633;">assertEquals</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> org.<span style="color: #006633;">junit</span>.<span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006633;">assertFalse</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> org.<span style="color: #006633;">junit</span>.<span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006633;">assertTrue</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.sql.Timestamp</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Calendar</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Date</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.List</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.annotation.Resource</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.apache.commons.lang.time.DateUtils</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.Criteria</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.SessionFactory</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.classic.Session</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.junit.Before</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.junit.Test</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.junit.runner.RunWith</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.test.context.ContextConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.test.context.junit4.SpringJUnit4ClassRunner</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.test.context.transaction.TransactionConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.transaction.annotation.Transactional</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.sourceallies.Person</span><span style="color: #339933;">;</span>
&nbsp;
@RunWith<span style="color: #009900;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
@ContextConfiguration
@TransactionConfiguration<span style="color: #009900;">&#40;</span>defaultRollback<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HibernateDateTimeTest <span style="color: #009900;">&#123;</span>
&nbsp;
	@Resource
	<span style="color: #000000; font-weight: bold;">private</span> SessionFactory sessionFactory<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Session currentSession<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> birthDateWithTime<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> birthDateWithoutTime<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> createDate<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> modifyDate<span style="color: #339933;">;</span>
&nbsp;
	@Before
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setUp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span><span style="color: #009900;">&#123;</span>
		currentSession <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">getCurrentSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		birthDateWithTime <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		birthDateWithoutTime <span style="color: #339933;">=</span> DateUtils.<span style="color: #006633;">truncate</span><span style="color: #009900;">&#40;</span>birthDateWithTime, <span style="color: #003399;">Calendar</span>.<span style="color: #006633;">DATE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		createDate <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		modifyDate <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Test
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSave<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		Person person <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Person<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;testFirst&quot;</span>, <span style="color: #0000ff;">&quot;testLast&quot;</span>, 
                      birthDateWithTime, createDate, modifyDate<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertFalse<span style="color: #009900;">&#40;</span>person.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>person.<span style="color: #006633;">getCreateDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>person.<span style="color: #006633;">getModifyDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		saveOrUpdate<span style="color: #009900;">&#40;</span>person<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Test
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testFind<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> people <span style="color: #339933;">=</span> findAll<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, people.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Person foundPerson <span style="color: #339933;">=</span> people.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getCreateDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getModifyDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertFalse<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>birthDateWithTime<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>birthDateWithoutTime<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getCreateDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>createDate<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getModifyDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>modifyDate<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> saveOrUpdate<span style="color: #009900;">&#40;</span>Person person<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		currentSession.<span style="color: #006633;">saveOrUpdate</span><span style="color: #009900;">&#40;</span>person<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		currentSession.<span style="color: #006633;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> findAll<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		Criteria criteria <span style="color: #339933;">=</span> currentSession.<span style="color: #006633;">createCriteria</span><span style="color: #009900;">&#40;</span>Person.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> people <span style="color: #339933;">=</span> criteria.<span style="color: #006633;">list</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> people<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here is the mapping for person.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">...
@<span style="color: #003399;">Entity</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #009900;">&#123;</span>
&nbsp;
	@Id
	@GeneratedValue<span style="color: #009900;">&#40;</span>strategy<span style="color: #339933;">=</span>GenerationType.<span style="color: #006633;">AUTO</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Long</span> id <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>1L<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> firstName<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> lastName<span style="color: #339933;">;</span>
&nbsp;
	@Column
	@Type<span style="color: #009900;">&#40;</span>type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;date&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> birthDate<span style="color: #339933;">;</span>
&nbsp;
	@Column
	@Type<span style="color: #009900;">&#40;</span>type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;timestamp&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> createDate<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> modifyDate<span style="color: #339933;">;</span>
	...
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>There are three <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Date.html">Date</a> fields: &#8216;birthdate&#8217;, &#8216;createDate&#8217;, and &#8216;modifyDate&#8217;.  The fields &#8216;birthDate&#8217; and &#8216;createDate&#8217; have a specified <a href="http://docs.jboss.org/hibernate/core/3.5/javadoc/org/hibernate/annotations/Type.html">Type</a>.  The field &#8216;modifyDate&#8217; however, does not have a specified Type.  The generated SQL from Hibernate is as follows.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> Person <span style="color: #66cc66;">&#40;</span>id bigint generated <span style="color: #993333; font-weight: bold;">BY</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> <span style="color: #993333; font-weight: bold;">AS</span> identity <span style="color: #66cc66;">&#40;</span>start <span style="color: #993333; font-weight: bold;">WITH</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span> 
birthDate date<span style="color: #66cc66;">,</span> createDate timestamp<span style="color: #66cc66;">,</span> firstName varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">255</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span> 
lastName varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">255</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span> modifyDate timestamp<span style="color: #66cc66;">,</span> <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #66cc66;">&#40;</span>id<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>We see that Hibernate created &#8216;birthDate&#8217; as a &#8216;Date&#8217; and the other two were created as a &#8216;Timestamp&#8217;.  The primary difference between &#8216;Date&#8217; and &#8216;Timestamp&#8217; in SQL is that &#8216;Timestamp&#8217; holds the date and time while the &#8216;Date&#8217; only holds the date.</p>
<p>At first glance this is not a big deal, but let&#8217;s take a closer look at the test.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">&nbsp;
	@Test
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSave<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		Person person <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Person<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;testFirst&quot;</span>, <span style="color: #0000ff;">&quot;testLast&quot;</span>, 
                           birthDateWithTime, createDate, modifyDate<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertFalse<span style="color: #009900;">&#40;</span>person.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>person.<span style="color: #006633;">getCreateDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>person.<span style="color: #006633;">getModifyDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		saveOrUpdate<span style="color: #009900;">&#40;</span>person<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Person is created with three <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Date.html">Dates</a> that all include date and time values.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">	@Test
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testFind<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> people <span style="color: #339933;">=</span> findAll<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, people.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Person foundPerson <span style="color: #339933;">=</span> people.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getCreateDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getModifyDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertFalse<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>birthDateWithTime<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertTrue<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getBirthDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>birthDateWithoutTime<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getCreateDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>createDate<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assertFalse<span style="color: #009900;">&#40;</span>foundPerson.<span style="color: #006633;">getModifyDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>modifyDate<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></div></div>

<p>When Hibernate retrieves a Person from the database the &#8216;createDate&#8217; and &#8216;modifyDate&#8217; have been converted to <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html">Timestamps</a>.  At first glance this doesn&#8217;t appear to be a big deal.  <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html">java.sql.Timestamp</a> extends <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Date.html">java.util.Date</a>.  But why are they not equal.  I found a helpful answer to this question in <a href="http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683">Effective Java (2nd Edition)</a> page 41.</p>
<p><em><br />
There are some classes in the Java platform libraries that do extend an instantiable<br />
class and add a value component. For example, java.sql.Timestamp<br />
extends java.util.Date and adds a nanoseconds field. The equals implementation<br />
for Timestamp does violate symmetry and can cause erratic behavior if<br />
Timestamp and Date objects are used in the same collection or are otherwise intermixed.<br />
The Timestamp class has a disclaimer cautioning programmers against<br />
mixing dates and timestamps. While you won’t get into trouble as long as you<br />
keep them separate, there’s nothing to prevent you from mixing them, and the<br />
resulting errors can be hard to debug. This behavior of the Timestamp class was a<br />
mistake and should not be emulated. (Bloch, Effective Java, 2nd Ed.)<br />
</em></p>
<p>If you want to read more about &#8216;equals&#8217; read chapter 3, Item 8 in <a href="http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683">Effective Java (2nd Edition)</a>.  Apart from a hack there are two primary ways to solve this issue.  The first way involves typing &#8216;createDate&#8217; and &#8216;modifyDate&#8217; to <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html">Timestamp</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">	...
	@Column
	@Type<span style="color: #009900;">&#40;</span>type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;date&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> birthDate<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Timestamp</span> createDate<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Timestamp</span> modifyDate<span style="color: #339933;">;</span>
        ...</pre></div></div>

<p>The second approach uses a custom <a href="http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/usertype/UserType.html">UserType</a>.  Here is a custom UserType that converts Timestamp to Date and vise versa.  There is a side effect with this solution.  Converting Timestamp to Date drops the nanosecond precision.  If this is not acceptable then the previous solution should be used.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.Serializable</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.sql.PreparedStatement</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.sql.ResultSet</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.sql.SQLException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.sql.Timestamp</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.sql.Types</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Date</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.HibernateException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.usertype.UserType</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> DateTimeUserType  <span style="color: #000000; font-weight: bold;">implements</span> UserType <span style="color: #009900;">&#123;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> sqlTypes<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		 <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #003399;">Types</span>.<span style="color: #006633;">TIMESTAMP</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;rawtypes&quot;</span><span style="color: #009900;">&#41;</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">Class</span> returnedClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #003399;">Date</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> equals<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> x, <span style="color: #003399;">Object</span> y<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> HibernateException <span style="color: #009900;">&#123;</span>
		 <span style="color: #000000; font-weight: bold;">return</span> x <span style="color: #339933;">==</span> y <span style="color: #339933;">||</span> <span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>x <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">||</span> y <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> x.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>y<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> hashCode<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> x<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> HibernateException <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> x.<span style="color: #006633;">hashCode</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> nullSafeGet<span style="color: #009900;">&#40;</span><span style="color: #003399;">ResultSet</span> rs, <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> names, <span style="color: #003399;">Object</span> owner<span style="color: #009900;">&#41;</span>
			<span style="color: #000000; font-weight: bold;">throws</span> HibernateException, <span style="color: #003399;">SQLException</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">Timestamp</span> timestamp <span style="color: #339933;">=</span> rs.<span style="color: #006633;">getTimestamp</span><span style="color: #009900;">&#40;</span>names<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>rs.<span style="color: #006633;">wasNull</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span>timestamp.<span style="color: #006633;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> nullSafeSet<span style="color: #009900;">&#40;</span><span style="color: #003399;">PreparedStatement</span> st, <span style="color: #003399;">Object</span> value, <span style="color: #000066; font-weight: bold;">int</span> index<span style="color: #009900;">&#41;</span>
			<span style="color: #000000; font-weight: bold;">throws</span> HibernateException, <span style="color: #003399;">SQLException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            st.<span style="color: #006633;">setNull</span><span style="color: #009900;">&#40;</span>index, <span style="color: #003399;">Types</span>.<span style="color: #006633;">TIMESTAMP</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">Date</span> date <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Date</span><span style="color: #009900;">&#41;</span> value<span style="color: #339933;">;</span>
            <span style="color: #003399;">Timestamp</span> timestamp <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Timestamp</span><span style="color: #009900;">&#40;</span>date.<span style="color: #006633;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            st.<span style="color: #006633;">setTimestamp</span><span style="color: #009900;">&#40;</span>index, timestamp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> deepCopy<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> value<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> HibernateException <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> value<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> isMutable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Serializable</span> disassemble<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> value<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> HibernateException <span style="color: #009900;">&#123;</span>
		 <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Serializable</span><span style="color: #009900;">&#41;</span> value<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> assemble<span style="color: #009900;">&#40;</span><span style="color: #003399;">Serializable</span> cached, <span style="color: #003399;">Object</span> owner<span style="color: #009900;">&#41;</span>
			<span style="color: #000000; font-weight: bold;">throws</span> HibernateException <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> cached<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> replace<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> original, <span style="color: #003399;">Object</span> target, <span style="color: #003399;">Object</span> owner<span style="color: #009900;">&#41;</span>
			<span style="color: #000000; font-weight: bold;">throws</span> HibernateException <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> original<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here is the way to use it in the Person class.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Entity</span>
@TypeDefs<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		@TypeDef<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;dateTimeUserType&quot;</span>, typeClass<span style="color: #339933;">=</span>DateTimeUserType.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #009900;">&#123;</span>
	...
	@Column
	@Type<span style="color: #009900;">&#40;</span>type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;date&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> birthDate<span style="color: #339933;">;</span>
&nbsp;
	@Column
	@Type<span style="color: #009900;">&#40;</span>type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;dateTimeUserType&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> createDate<span style="color: #339933;">;</span>
&nbsp;
	@Column
	@Type<span style="color: #009900;">&#40;</span>type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;dateTimeUserType&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> modifyDate<span style="color: #339933;">;</span>
        ...</pre></div></div>

<p>Either of these solutions will prevent the &#8216;equals&#8217; issue that we encountered before.  This issue is not a Hibernate issue it is truly a Java issue as is stated in <a href="http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683">Effective Java (2nd Edition)</a>.  Hibernate can be challenging enough without these subtle issues that are easy to miss until a bug is reported.</p>
<p>Here is the complete code. <a href="http://blogs.sourceallies.com/wp-content/uploads/2012/02/HibernateDateTime3.zip" > Hibernate Logging Zip </a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate Logging</title>
		<link>http://blogs.sourceallies.com/2012/01/hibernate-logging/</link>
		<comments>http://blogs.sourceallies.com/2012/01/hibernate-logging/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 14:54:22 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[interceptor]]></category>
		<category><![CDATA[logging]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2541</guid>
		<description><![CDATA[Through the years I&#8217;ve encountered a recurring requirement.  Clients need to log changes to the database for auditing and legal purposes.  To satisfy this requirement you could add logging to every save/update/delete call in your code.  Or better yet, you could create an aspect that wraps these calls.  While these would [...]]]></description>
			<content:encoded><![CDATA[<p>Through the years I&#8217;ve encountered a recurring requirement.  Clients need to log changes to the database for auditing and legal purposes.  To satisfy this requirement you could add logging to every save/update/delete call in your code.  Or better yet, you could create an <a href="http://goo.gl/DNo6a">aspect</a> that wraps these calls.  While these would certainly work Hibernate provides a convenient <a href="http://goo.gl/K0pJr">interceptor</a>.</p>
<p>In this article I will show you how to add a simple logger to Hibernate.<br />
<span id="more-2541"></span></p>
<h2>Start with a Test</h2>
<p>As an avid <a href="http://goo.gl/1KEI0">TDD </a> practitioner I will of coarse start with a test.  Here is the final version of the test that I used to drive my code.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.logging</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> org.<span style="color: #006633;">junit</span>.<span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006633;">assertEquals</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">mock</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">verify</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">verifyNoMoreInteractions</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Date</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.List</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.annotation.Resource</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.apache.commons.logging.Log</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.Criteria</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.SessionFactory</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.classic.Session</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.junit.Before</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.junit.Test</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.junit.runner.RunWith</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.test.context.ContextConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.test.context.junit4.SpringJUnit4ClassRunner</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.transaction.annotation.Transactional</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.sourceallies.Person</span><span style="color: #339933;">;</span>
&nbsp;
@RunWith<span style="color: #009900;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
@ContextConfiguration
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HibernateInterceptorTest <span style="color: #009900;">&#123;</span>
&nbsp;
	@Resource
	<span style="color: #000000; font-weight: bold;">private</span> SessionFactory sessionFactory<span style="color: #339933;">;</span>
&nbsp;
	@Resource
	<span style="color: #000000; font-weight: bold;">private</span> HibernateInterceptor hibernateInterceptor<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Session currentSession<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Log logger<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">Date</span> NOW <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	@Before
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setUp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		logger <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span>Log.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		currentSession <span style="color: #339933;">=</span> sessionFactory.<span style="color: #006633;">getCurrentSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		hibernateInterceptor.<span style="color: #006633;">setLogger</span><span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Test
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSaveLogging<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		saveOrUpdate<span style="color: #009900;">&#40;</span>createPerson<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, findAll<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		verify<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Saving Person [firstName=testFirst, lastName=testLast, birthDate=&quot;</span> <span style="color: #339933;">+</span> NOW <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;].&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		verifyNoMoreInteractions<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Test
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testUpdateLogging<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		saveOrUpdate<span style="color: #009900;">&#40;</span>createPerson<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> people <span style="color: #339933;">=</span> findAll<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, people.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		Person firstPerson <span style="color: #339933;">=</span> people.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		firstPerson.<span style="color: #006633;">setFirstName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;testFirst2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		saveOrUpdate<span style="color: #009900;">&#40;</span>firstPerson<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		currentSession.<span style="color: #006633;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		verify<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Saving Person [firstName=testFirst, lastName=testLast, birthDate=&quot;</span> <span style="color: #339933;">+</span> NOW <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;].&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		verify<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Updating Person [firstName=testFirst2, lastName=testLast, birthDate=&quot;</span> <span style="color: #339933;">+</span> NOW <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;].&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		verifyNoMoreInteractions<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Test
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testDeleteLogging<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		saveOrUpdate<span style="color: #009900;">&#40;</span>createPerson<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> people <span style="color: #339933;">=</span> findAll<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, people.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		Person firstPerson <span style="color: #339933;">=</span> people.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		delete<span style="color: #009900;">&#40;</span>firstPerson<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		currentSession.<span style="color: #006633;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		verify<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Saving Person [firstName=testFirst, lastName=testLast, birthDate=&quot;</span> <span style="color: #339933;">+</span> NOW <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;].&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		verify<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Deleting Person [firstName=testFirst, lastName=testLast, birthDate=&quot;</span> <span style="color: #339933;">+</span> NOW <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;].&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		verifyNoMoreInteractions<span style="color: #009900;">&#40;</span>logger<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> saveOrUpdate<span style="color: #009900;">&#40;</span>Person person<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		currentSession.<span style="color: #006633;">saveOrUpdate</span><span style="color: #009900;">&#40;</span>person<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		currentSession.<span style="color: #006633;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> delete<span style="color: #009900;">&#40;</span>Person person<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		currentSession.<span style="color: #006633;">delete</span><span style="color: #009900;">&#40;</span>person<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> findAll<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		Criteria criteria <span style="color: #339933;">=</span> currentSession.<span style="color: #006633;">createCriteria</span><span style="color: #009900;">&#40;</span>Person.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		List<span style="color: #339933;">&lt;</span>Person<span style="color: #339933;">&gt;</span> people <span style="color: #339933;">=</span> criteria.<span style="color: #006633;">list</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> people<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Person createPerson<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		Person person <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Person<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;testFirst&quot;</span>, <span style="color: #0000ff;">&quot;testLast&quot;</span>, NOW<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> person<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I used a mock logger to gather information from the interceptor.</p>
<h2>Spring Configuration</h2>
<p>Here is the configuration required for the interceptor.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                ...
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;dataSource&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;entityInterceptor&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;hibernateInterceptor&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;transactionManager&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.orm.hibernate3.HibernateTransactionManager&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;sessionFactory&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         ...	
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;com.sourceallies&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        ...</pre></div></div>

<p>The &#8216;entityInterceptor&#8217; property on the &#8217;sessionFactory&#8217; takes a Hibernate interceptor.</p>
<h2>Entity</h2>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Entity</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #009900;">&#123;</span>
&nbsp;
	@Id
	@GeneratedValue<span style="color: #009900;">&#40;</span>strategy<span style="color: #339933;">=</span>GenerationType.<span style="color: #006633;">AUTO</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Long</span> id <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>1L<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> firstName<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> lastName<span style="color: #339933;">;</span>
&nbsp;
	@Column
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Date</span> birthDate<span style="color: #339933;">;</span>
...
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;Person [firstName=&quot;</span> <span style="color: #339933;">+</span> firstName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;, lastName=&quot;</span>
				<span style="color: #339933;">+</span> lastName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;, birthDate=&quot;</span> <span style="color: #339933;">+</span> birthDate <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;]&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>For this example you need to implement the &#8216;toString&#8217; method on the entity being logged.</p>
<h2>Interceptor</h2>
<p>Here is the interceptor code.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.logging</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.Serializable</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.apache.commons.logging.Log</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.apache.commons.logging.LogFactory</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.EmptyInterceptor</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hibernate.type.Type</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.stereotype.Component</span><span style="color: #339933;">;</span>
&nbsp;
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HibernateInterceptor <span style="color: #000000; font-weight: bold;">extends</span> EmptyInterceptor <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> 1L<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> Log logger <span style="color: #339933;">=</span> LogFactory.<span style="color: #006633;">getLog</span><span style="color: #009900;">&#40;</span>HibernateInterceptor.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> onDelete<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> entity, <span style="color: #003399;">Serializable</span> id, <span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> state,
			<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> propertyNames, Type<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> types<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		log<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Deleting&quot;</span>, id, entity<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">onDelete</span><span style="color: #009900;">&#40;</span>entity, id, state, propertyNames, types<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> onFlushDirty<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> entity, <span style="color: #003399;">Serializable</span> id,
			<span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> currentState, <span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> previousState,
			<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> propertyNames, Type<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> types<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		log<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Updating&quot;</span>, id, entity<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">onFlushDirty</span><span style="color: #009900;">&#40;</span>entity, id, currentState, previousState,
				propertyNames, types<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> onSave<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> entity, <span style="color: #003399;">Serializable</span> id, <span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> state,
			<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> propertyNames, Type<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> types<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		log<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Saving&quot;</span>, id, entity<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">onSave</span><span style="color: #009900;">&#40;</span>entity, id, state, propertyNames, types<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> setLogger<span style="color: #009900;">&#40;</span>Log logger<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">logger</span> <span style="color: #339933;">=</span> logger<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> log<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> action, <span style="color: #003399;">Serializable</span> id, <span style="color: #003399;">Object</span> entity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		logger.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span>action <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> entity <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>While the &#8216;onSave&#8217; and &#8216;onDelete&#8217; methods are clearly named the &#8216;onUpdate&#8217; method appears to be missing.  With a little research it quickly becomes obvious that &#8216;onFlushDirty&#8217; is used for updates.</p>
<p>Logging database activity is this simple.</p>
<p>Here is the complete code. <a href="http://blogs.sourceallies.com/wp-content/uploads/2012/01/HibernateLogging.zip" > Hibernate Logging Zip </a></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2012/01/hibernate-logging/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Next Step in Agility</title>
		<link>http://blogs.sourceallies.com/2011/10/next-step-in-agility/</link>
		<comments>http://blogs.sourceallies.com/2011/10/next-step-in-agility/#comments</comments>
		<pubDate>Sat, 01 Oct 2011 14:08:32 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2480</guid>
		<description><![CDATA[I often find that teams that have adopted Agile practices quickly plateau.  They often start by scheduling a daily stand up, planning in iterations, take time for a retrospective, and modify their estimation process.  These are common first steps in the agile adoption process.  Teams have varied success and commitments to these [...]]]></description>
			<content:encoded><![CDATA[<p>I often find that teams that have adopted Agile practices quickly plateau.  They often start by scheduling a daily <a href="http://en.wikipedia.org/wiki/Stand-up_meeting">stand up</a>, planning in <a href="http://en.wikipedia.org/wiki/Iterative_and_incremental_development">iterations</a>, take time for a <a href="http://en.wikipedia.org/wiki/Agile_software_development#Software_development_life_cycle">retrospective</a>, and modify their estimation process.  These are common first steps in the agile adoption process.  Teams have varied success and commitments to these practices but nevertheless these are the low hanging fruits in the Agile adoption journey.<br />
<span id="more-2480"></span><br />
Once a team has plateaued, where do they go from there?  After eight years of leading Agile software development teams a consistent thread has emerged.  Teams should work to create an automated continuous deployment process.  I intentionally did not use the work <a href="http://en.wikipedia.org/wiki/Continuous_integration">continuous integration</a>(CI).  This is not to say that what I&#8217;m proposing does not involve continuous integration.  However the word has been misused by numerous teams. Many teams that I work with only use their CI build to run a few unit tests.  While this is an important first step it fails to address the systemic problem within our industry of integrating our products together.</p>
<p>If your team spends more than an afternoon deploying their product to a test region or to production then you need to start chipping away at this next step.  Agile software development emphasizes <a href="http://agilemanifesto.org/">working software</a>.  While this seems like a no-brainer, we often neglect the core issues that prevent our software from working.  The most significant one being that we often do not know our software does not work until it is too late.</p>
<p>The single most powerful change that you can bring to your software development team is continuous deployment.  What does this mean?  I&#8217;m not suggesting that you auto deploy to production.  I have not worked with an organization yet that is ready to make this leap of faith.  Instead I&#8217;m encouraging you to:</p>
<ol>
<li>automate your deployment process and run it every time your check in your code.</li>
<li>run a couple of user tests that walk through the most common end-to-end flows</li>
</ol>
<p>While this may seem fairly straight forward this is difficult to complete.  Much of this depends on your architecture, infrastructure and policies.  To illustrate this point let&#8217;s look at a project that I lead a couple of years ago.  In order to auto deploy our project and run test against our product we needed:</p>
<ol>
<li>to have admin privileges on 5 dedicated database.</li>
<li>to create the database from versioned scripts</li>
<li>to load test data in each database</li>
<li>to have an application server on our CI box.</li>
<li>to have a message queue on our CI box.</li>
<li>to have three web services deployed and running</li>
<li>to have a build process that can automatically build and deploy an EAR to the application server</li>
</ol>
<p>Policies, licensing and time are the largest barrier standing in the way of achieving this in any organization.  This example may be more or less complex than the needs on your project.  Nevertheless, in my experience working to break down these barriers is essential to delivering working software.  Being able to address deployment issues as they come up is much less stressful than standing in a cube after hours trying to figure out why this stupid app won&#8217;t work with managers asking if you are &#8220;done yet&#8221;.  </p>
<p>Policies can be changed if you track the amount of wasted time as it relates to deployment delays.  Licensing costs can be accounted for or avoided (open source) if managers understand the savings. And as far as time goes, I&#8217;m more willing to put some time up front so I don&#8217;t have to loose my nights and weekends at the end of the project.</p>
<p>I know that this is possible.  I have seen it work on numerous projects and team.  Take the next step in Agility and automate your deployment process.  Ensure that your software works by running a few end-to-end user tests.  The effort is worth it.  Your time and sanity is worth it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/10/next-step-in-agility/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Learning a new Language</title>
		<link>http://blogs.sourceallies.com/2011/09/learning-a-new-language/</link>
		<comments>http://blogs.sourceallies.com/2011/09/learning-a-new-language/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 16:18:17 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2453</guid>
		<description><![CDATA[I attended a No Fluff Just Stuff Symposium a few weeks ago.  One of the main emphasis during the weekend was learning new languages that are available on the JVM.  While there are a variety of reasons that we need to take time to learn new programming languages, one of the most profound [...]]]></description>
			<content:encoded><![CDATA[<p>I attended a <a href="http://nofluffjuststuff.com/home/main">No Fluff Just Stuff Symposium</a> a few weeks ago.  One of the main emphasis during the weekend was learning new languages that are available on the <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine">JVM</a>.  While there are a variety of reasons that we need to take time to learn new programming languages, one of the most profound is learning to think about problems differently.</p>
<h2>Paradigm Shift</h2>
<p>When I entered the development scene I was immersed in <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">Object Oriented</a> programming.  As a result, I tend to think of good design in objects.  A few years ago I began to learn and apply <a href="http://groovy.codehaus.org/">Groovy</a>.  With <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29">closures</a> I was able to bleed into the realm of <a href="http://en.wikipedia.org/wiki/Functional_programming">Functional</a> programming.  This gave me a small taste of a new paradigm.  I thought of new ways to solve problems that I couldn&#8217;t see with Java.  I can only imagine how much more I could learn if I developed exclusively in a Functional language for several months.<br />
<span id="more-2453"></span><br />
I tend to see two camps when it comes to learning new languages.  The first camp thinks that the language that they know is sufficient for solving all programming problems.  The second camp runs after the newest hot thing and divorces themselves from their old language.  Neither extreme is healthy.  We need to see languages as tools.  A hammer is not good for solving all problems.  Sure you might be able to turn a screw with the claw of a hammer but why would you.  We need to understand our problems first and select a language that solves it best.  </p>
<p>JVM languages allow us to make this decision at the last responsible moment.  We can select a JVM language that seems appropriate and begin coding.  If it becomes clear later that this language is not well suited to solve this problem then we can change our mind.  The JVM provides a single platform for us to use the best tool for the job.  We can even use multiple languages to develop one system.  The JVM is an amazing canvas for agility.</p>
<h2>Detour</h2>
<p>Now I want to take what may seem like a major detour.  However I would suggest that this does not stray all that far.  We need to extend our effort to become multilingual beyond the JVM.  As professionals we would benefit from learning the language of different business areas.  Management, Testers, and Business Analysts solve problems in different language paradigms.</p>
<p>Many developers begin to tune out as I mention management.  Feelings of frustration begin to take over.  We can tolerate BA&#8217;s and Testers for the most part but management is just a waste of time.  The pain and frustration from the past takes over and we just tune out.  We code in secret and try not to disturb the gods of management.  We avoid them and hopefully they will leave us alone.</p>
<p>While I&#8217;m not here to say that all management is just massively misunderstood and we need to forgive and forget, we do need to learn to communicate.  We often contribute to our own misery.  We are either silent or we speak in a language that makes no sense.  We need to learn their language.</p>
<h2>Speaking the Same Language</h2>
<p>Before I proceed let me make a very important side note.  Not all managers are open to an intelligent and rational discussions.  Some have given in to money and power and they just want to be right no matter the cost.  While this can be true, I think that there are many managers that can be reasonable.  The challenge is not intellectual but one of language.</p>
<p>How do managers think?  Well one simple way to find out is to listen to them.  What are they focused on?  What excites them?  What frustrates them?  But the most important question is why.  Why are they focused on certain things?  The question of why delves into the area of motivation.  What motivates management?  Sure we can go for the easy answer of money, but is that the whole story?  </p>
<h2>Expanding our Library</h2>
<p>Once you start listening I believe we need to move to education.  We need to add a few business books to our technical library.  Begin to understand the information that managers are focused on.  Take time to understand how they get information and how that effects their decisions.  And now it&#8217;s time for a big leap.  How can we provide information from our development effort that can influence management decisions.  Now I want to caution you.  This will not always work.  But if we are not speaking manager-eez then we can not expect to influence their decisions.  I see this same challenge in my marriage.  My wife doesn&#8217;t focus on the same things that I do.  Nevertheless, over time we&#8217;ve learned to speak each others language.  We work to bridge this divide because we &#8220;care&#8221; about each other.  I know I brought out a feeling word.  We can try to avoid the &#8220;F&#8221; word, but if we don&#8217;t care enough to take the first step to bridge the technical and management divide who will?</p>
<h2>Balancing Act</h2>
<p>Once you have a good understanding of how your management team makes decisions, you need to get the right information to them.  While every company and manager is different there tend to be some common ingredients in their decision making process.  The first ingredient is <a href="http://en.wikipedia.org/wiki/Return_on_Investment">return on investment</a> (ROI).  The second ingredient is generally <a href="http://en.wikipedia.org/wiki/Risk_management">risk management</a>.</p>
<p>As a developer these tend to make me irritated.  ROI appears to be something that can not be accurately measured and risk management just results in more work.  However these are things that we deal with in our personal lives all the time.  Marriage, 401K, children, cars, investments, homes all require us to consider ROI and risk.  After buying three homes and selling two I am painfully aware of ROI and the need for risk assessment.  Each purchase has different factors.  A starter home needs to be something that I can resell in a few years.  However starter homes often require a lot of maintenance and updating.  A retirement home needs to be built to last.  Similarly, every management decision has specific factors that drive the decision.  </p>
<p>In software development the major factors tend to be: time-to-market, timeliness, development cost, maintenance costs, usability, scalability, security and features.  The right product at the wrong time results in a useless product.  A great <a href="http://en.wikipedia.org/wiki/8-track_tape">8 track player</a> delivered in 1980 as the <a href="http://en.wikipedia.org/wiki/Cassette_tape">cassette tape</a> market was on the rise, would be a waste of money.  If you were one of the 70 million customers of Sony’s PlayStation that had their information stolen this year, all the other features became less important.  Developing software, or products, is not just a matter of putting the correct components together.  Good managers try to balance all the moving parts.</p>
<h2>Show me the Facts</h2>
<p>So how can we provide valuable information?  One vital piece of information is the project <a href="http://en.wikipedia.org/wiki/Burn_down_chart">burndown</a>.  A burndown projects the projected completion date based on the historical <a href="http://en.wikipedia.org/wiki/Velocity_%28software_development%29">velocity</a> and the size of the feature <a href="http://en.wikipedia.org/wiki/Scrum_%28development%29#Product_backlog">backlog</a>.  But marching towards the finish line does not always equate to a valuable product.  Regular demos to the customer allows us to calibrate the relevance and usability.  Tracking the feedback from these demos helps us measure the value of the current product.</p>
<p>Another factor to measure is the maintainability of a product.  As we set a development pace we need to determine if this pace is creating waste.  Managers have to weigh the cost of speedy development with the cost of long-term maintenance.  But without any data this decision can not be made. Are developers just wasting time trying to make a Rolls-Royce when we just need a Pinto?  We need facts not opinions to steer the ship of management.  Instead of pretending that I am an expert in this area I am going to recommend that you read two of Neal Ford&#8217;s articles on &#8220;Evolutionary architecture and emergent design&#8221;.  </p>
<ul>
<li><a href="http://www.ibm.com/developerworks/java/library/j-eaed17/index.html">Evolutionary architecture and emergent design: Environmental considerations for design, Part 1</a></li>
<li><a href="http://www.ibm.com/developerworks/java/library/j-eaed6/index.html">Evolutionary architecture and emergent design: Emergent design through metrics</a></li>
</ul>
<p>While the topic may be a little different from this blog these articles contain amazing insight on gathering, analyzing and visualizing <a href="http://en.wikipedia.org/wiki/Technical_debt">technical debt</a>.  Technical debt is that elusive beast that we feed when we, with the best intentions, just try to &#8220;get-er done&#8221;.  The fatter this beast gets the harder it is to make changes during the development process and during long-term maintenance.  In this case harder means more costly.  </p>
<h2>Summary</h2>
<p>As developers we are focused on language.  We use words to create software.  We translate business words into code.  We are in fact professional interpreters.  We use our multilingual skills to translate concepts into working software.  But when it comes to bridging the communication divide between software development and management decisions we often give up.  We try to use emotion pleas or technical words to effect change but people quickly stop listening.</p>
<p>As professional, multilingual, translators we need to focus our skills on effectively communicating with management.  We need to understand their domain and gather valuable and relevant information that can guide their decisions.  Instead of avoiding management we need to engage them.  We need to gather information that only we poses and translate it into information that makes sense to critical decision makers.  We need to become part of the solution instead of contributing to an overwhelming problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/09/learning-a-new-language/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spring Injection with @Resource, @Autowired and @Inject</title>
		<link>http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/</link>
		<comments>http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 12:00:09 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[@Autowired]]></category>
		<category><![CDATA[@Inject]]></category>
		<category><![CDATA[@Resource]]></category>
		<category><![CDATA[Injection]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2350</guid>
		<description><![CDATA[Overview
I&#8217;ve been asked several times to explain the difference between injecting Spring beans with &#8216;@Resource&#8217;, &#8216;@Autowired&#8217;, and &#8216;@Inject&#8217;.  While I received a few opinions from colleagues and read a couple of posts on this topic I didn&#8217;t feel like I had a complete picture.
Annotations


Annotation
Package
Source


@Resource
javax.annotation
Java


@Inject
javax.inject
Java


@Qualifier
javax.inject
Java


@Autowired
org.springframework.bean.factory
Spring



In order to explore the behavior of each annotation I fired [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>I&#8217;ve been asked several times to explain the difference between injecting Spring beans with &#8216;@Resource&#8217;, &#8216;@Autowired&#8217;, and &#8216;@Inject&#8217;.  While I received a few opinions from colleagues and read a couple of posts on this topic I didn&#8217;t feel like I had a complete picture.</p>
<h4>Annotations</h4>
<table>
<tr>
<th>Annotation</th>
<th>Package</th>
<th>Source</th>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Resource</td>
<td style="text-align:left; padding-left:5px;">javax.annotation</td>
<td style="text-align:left; padding-left:5px;">Java</td>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Inject</td>
<td style="text-align:left; padding-left:5px;">javax.inject</td>
<td style="text-align:left; padding-left:5px;">Java</td>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Qualifier</td>
<td style="text-align:left; padding-left:5px;">javax.inject</td>
<td style="text-align:left; padding-left:5px;">Java</td>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Autowired</td>
<td style="text-align:left; padding-left:5px;">org.springframework.bean.factory</td>
<td style="text-align:left; padding-left:5px;">Spring</td>
</tr>
</table>
<p><br/><br />
In order to explore the behavior of each annotation I fired up <a href="http://www.springsource.com/developer/sts">Spring Tool Suite</a> and started debugging the code.  I used Spring 3.0.5.RELEASE in my research. The following is a summary of my findings.<br />
<span id="more-2350"></span></p>
<h2>The Code</h2>
<p>I wanted to know how &#8216;@Resource&#8217;, &#8216;@Autowired&#8217;, and &#8216;@Inject&#8217; resolved dependencies.  I created an interface called &#8216;Party&#8217; and created two implementations classes.  This allowed me to inject beans without using the concrete type.  This provided the flexibility I needed to determine how Spring resolves beans when there are multiple type matches.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>&#8216;Person&#8217; is a component and it implements &#8216;Party&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.person</span><span style="color: #339933;">;</span>
...
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #000000; font-weight: bold;">implements</span> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>&#8216;Organization&#8217; is a component and it implements &#8216;Party&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.organization</span><span style="color: #339933;">;</span>
...
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Organization <span style="color: #000000; font-weight: bold;">implements</span> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I setup a Spring context that scans both of these packages for beans marked with &#8216;@Component&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;com.sourceallies.organization&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;com.sourceallies.person&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<h2>Tests</h2>
<h3>Test 1: Ambiguous Beans</h3>
<p>In this test I injected a &#8216;Party&#8217; bean that has multiple implementations in the Spring context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>In all three cases a &#8216;NoSuchBeanDefinitionException&#8217; is thrown.  While this exception&#8217;s name implies that no beans were found, the message explains that two beans were found.  All of these annotations result in the same exception.</em></strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">NoSuchBeanDefinitionException</span><span style="color: #339933;">:</span> 
No unique bean of type <span style="color: #009900;">&#91;</span>com.<span style="color: #006633;">sourceallies</span>.<span style="color: #006633;">Party</span><span style="color: #009900;">&#93;</span> is defined<span style="color: #339933;">:</span> 
expected single matching bean but found <span style="color: #cc66cc;">2</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>organization, person<span style="color: #009900;">&#93;</span></pre></div></div>

<h3>Test 2: Field Name</h3>
<p>In this test I named the Party field person.  By default beans marked with &#8216;@Component&#8217; will have the same name as the class.  Therefore the name of the class &#8216;Person&#8217; is person.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>

<p>&#8216;@Resource&#8217; can also take an optional &#8216;name&#8217; attribute.  This is equivalent to the &#8216;@Resource&#8217; code above.  In this case the field variable name remains &#8216;party&#8217;.  There is no equivalent syntax for &#8216;@Autowired&#8217; or &#8216;@Inject&#8217;.  Instead you would have to use a &#8216;@Qualifier&#8217;.  This syntax will be covered later.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All four of these styles inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 3: Field Type</h3>
<p>In this test I changed the type to be a &#8216;Person&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Person party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Person party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Person party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 4: Default Name Qualifier</h3>
<p>In this test I use a &#8216;@Qualifier&#8217; annotation to point to the default name of the &#8216;Person&#8217; component.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 5: Qualified Name</h3>
<p>I added a &#8216;@Qualifier&#8217; annotation to the &#8216;Person&#8217; class</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.person</span><span style="color: #339933;">;</span>
...
@<span style="color: #003399;">Component</span>
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #000000; font-weight: bold;">implements</span> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In this test I use a &#8216;@Qualifier&#8217; annotation to point to the qualified name of the &#8216;Person&#8217; component.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 6: List of Beans</h3>
<p>In this test I inject a list of beans.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Party<span style="color: #339933;">&gt;</span> parties<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Party<span style="color: #339933;">&gt;</span> parties<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Party<span style="color: #339933;">&gt;</span> parties<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject 2 beans into the list.  This can also be accomplished with a &#8216;@Qualifier&#8217;.  Each bean marked with a specific qualifier will be added to the list.</em></strong></p>
<h3>Test 7: Conflicting messages</h3>
<p>In this test I add a bad &#8216;@Qualifier&#8217; and a matching field name.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>In this case the field marked with &#8216;@Resource&#8217; uses the field name and ignores the &#8216;@Qualifier&#8217;.  As a result the &#8216;Person&#8217; bean is injected.</em></strong></p>
<p><strong><em>However the &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; field throw a &#8216;NoSuchBeanDefinitionException&#8217; error because it can not find a bean that matches the &#8216;@Qualifier&#8217;.</em></strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"> org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">NoSuchBeanDefinitionException</span><span style="color: #339933;">:</span> 
No matching bean of type <span style="color: #009900;">&#91;</span>com.<span style="color: #006633;">sourceallies</span>.<span style="color: #006633;">Party</span><span style="color: #009900;">&#93;</span> found <span style="color: #000000; font-weight: bold;">for</span> dependency<span style="color: #339933;">:</span> 
expected at least <span style="color: #cc66cc;">1</span> bean which qualifies as autowire candidate <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #000000; font-weight: bold;">this</span> dependency. 
<span style="color: #006633;">Dependency</span> annotations<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>@org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">Autowired</span><span style="color: #009900;">&#40;</span>required<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>,
@org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">Qualifier</span><span style="color: #009900;">&#40;</span>value<span style="color: #339933;">=</span>bad<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Conclusions</h2>
<p>With the exception of test 2 &#038; 7 the configuration and outcomes were identical.  When I looked under the hood I determined that the &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; annotation behave identically.  Both of these annotations use the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.html">&#8216;AutowiredAnnotationBeanPostProcessor&#8217;</a> to inject dependencies. &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; can be used interchangeable to inject Spring beans.  However the &#8216;@Resource&#8217; annotation uses the <a href="http://static.springsource.org/spring/docs/3.1.0.M2/javadoc-api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html">&#8216;CommonAnnotationBeanPostProcessor&#8217;</a> to inject dependencies.  Even though they use different post processor classes they all behave nearly identically.  Below is a summary of their execution paths.</p>
<p><strong>@Autowired and @Inject</strong></p>
<ol>
<li>Matches by Type</li>
<li>Restricts by Qualifiers</li>
<li>Matches by Name</li>
</ol>
<p><strong>@Resource</strong></p>
<ol>
<li>Matches by Name</li>
<li>Matches by Type</li>
<li>Restricts by Qualifiers (ignored if match is found by name)</li>
</ol>
<p>While it could be argued that &#8216;@Resource&#8217; will perform faster by name than &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; it would be negligible.  This isn&#8217;t a sufficient reason to favor one syntax over the others.  I do however favor the &#8216;@Resource&#8217; annotation for it&#8217;s concise notation style.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>You may argue that they can be equal concise if you use the field name to identify the bean name.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>

<p>True enough, but what happens if you want to <a href="http://en.wikipedia.org/wiki/Code_refactoring">refactor</a> your code?  By simply renaming the field name you&#8217;re no longer referring to the same bean.   I recommend the following practices when wiring beans with annotations.</p>
<p><strong>Spring Annotation Style Best Practices</strong></p>
<ol>
<li>Explicitly name your component [@Component("beanName")]</li>
<li>Use &#8216;@Resource&#8217; with the &#8216;name&#8217; attribute [@Resource(name="beanName")]</li>
<li>Avoid &#8216;@Qualifier&#8217; annotations unless you want to create a list of similar beans.  For example you may want to mark a set of rules with a specific &#8216;@Qualifier&#8217; annotation.  This approach makes it simple to inject a group of rule classes into a list that can be used for processing data.</li>
<li>Scan specific packages for components [context:component-scan base-package="com.sourceallies.person"].  While this will result in more component-scan configurations it reduces the chance that you&#8217;ll add unnecessary components to your Spring context.</li>
</ol>
<p>Following these guidelines will increase the readability and stability of your Spring annotation configurations.</p>
<h2>Related Links</h2>
<p><a href="/2011/06/testing-spring-wiring/"> Testing Spring Wiring</a><br />
<a href="http://beanoh.org"> Beanoh Spring Wiring Test Framework</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Debugging memory leaks with VisualVM</title>
		<link>http://blogs.sourceallies.com/2011/07/debugging-memory-leaks-with-visualvm/</link>
		<comments>http://blogs.sourceallies.com/2011/07/debugging-memory-leaks-with-visualvm/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 12:45:01 +0000</pubDate>
		<dc:creator>Cory Wandling</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[vm]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2389</guid>
		<description><![CDATA[At work I had run into a memory leak when scrolling through large result sets returned from Hibernate.  I thought I had fixed it by performing a evict()/clear()/flush() in the HibernateTemplate that I was using but suddenly the leak was back.  I was using VisualVm to monitor the heap so I started poking [...]]]></description>
			<content:encoded><![CDATA[<p>At work I had run into a memory leak when scrolling through large result sets returned from Hibernate.  I thought I had fixed it by performing a evict()/clear()/flush() in the HibernateTemplate that I was using but suddenly the leak was back.  I was using <a href="http://visualvm.java.net/">VisualVm</a> to monitor the heap so I started poking around to see if there was anything to help diagnose where the leak was.<br />
<span id="more-2389"></span></p>
<p>First thing I did was to take a heap dump.</p>
<p><img src="http://www.jroller.com/clwandling/resource/memory_leak_1.png"></p>
<p>I selected the classes and I see</p>
<p><img src="http://www.jroller.com/clwandling/resource/memory_leak_2.png"></p>
<p>
Well <strong>THAT</strong> was not helpful.  It turns out that the leak is in a class that only has one instance and it is <em><b>holding onto</b></em> thousands of objects.<br />
Then on the summary page I notice the &#8220;Find 20 biggest objects by retained size:&#8221;.</p>
<p><img src="http://www.jroller.com/clwandling/resource/memory_leak_4.png"></p>
<p>I click it and a <em>long</em> time later I see</p>
<p><img src="http://www.jroller.com/clwandling/resource/memory_leak_3.png"></p>
<p>Shazam! There it is! In this faked up example I built there is a single Stack instance but it&#8217;s <em><b>retained size</b></em> is huge.  That because VisualVM computed not just the size of that object but the sizes of all of the objects it was holding onto.  How sweet is that.  I found my memory leak in like 5 minutes.</p>
<p>Another useful tool!</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/07/debugging-memory-leaks-with-visualvm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an Open Source Project</title>
		<link>http://blogs.sourceallies.com/2011/07/creating-an-open-source-project/</link>
		<comments>http://blogs.sourceallies.com/2011/07/creating-an-open-source-project/#comments</comments>
		<pubDate>Fri, 01 Jul 2011 05:00:11 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2118</guid>
		<description><![CDATA[Open Sourcing Software
I&#8217;ve been using open source software for many years, but I&#8217;ve never open sourced my own project.  This blog is a record of my experience as I start this journey.   The resulting project can be found at http://beanoh.org.
Where
First I had to decide where to store the code.  There are several [...]]]></description>
			<content:encoded><![CDATA[<h1>Open Sourcing Software</h1>
<p>I&#8217;ve been using open source software for many years, but I&#8217;ve never open sourced my own project.  This blog is a record of my experience as I start this journey.   The resulting project can be found at <a href="http://beanoh.org">http://beanoh.org</a>.</p>
<h2>Where</h2>
<p>First I had to decide where to store the code.  There are several popular (<a href="http://en.wikipedia.org/wiki/Comparison_of_open_source_software_hosting_facilities#Popularity">Comparison of open source software hosting</a>) open source hosting options. I chose GitHub (<a href="http://github.com">github.com</a>) because I already had an account and I&#8217;m comfortable using Git.  Furthermore, GitHub provides intuitive tools that make it easy to manage a project.  I can setup an <a href="https://github.com/blog/674-introducing-organizations">organization</a> so multiple <a href="http://www.sourceallies.com">Source Allies</a> employees can have commit rights on this project.  GitHub also has an integrated <a href="https://github.com/blog/411-github-issue-tracker">issue and feature tracking system</a> that connects commits with tickets.  Overall I am very impressed with GitHub.</p>
<p><span id="more-2118"></span></p>
<h2>License</h2>
<p>Before I push my code into GitHub I need to choose a liscense.  This seems very overwhelming.  I&#8217;m not a lawyer so how can I understand what each license provides?  I started by searching for comparison charts.   Out of these results I found the following comparisons helpful:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Comparison_of_free_software_licenses">Comparison of free software licenses</a></li>
<li><a href="http://www.shafqatahmed.com/WindowsLiveWriter/OpenSourceLicenseComparison.png">Open Source License Comparison</a></li>
<li><a href="http://knol.google.com/k/open-source-licenses-for-dummies#">open source licenses for dummies</a></li>
</ul>
<p>I feel like I understand the differences a little better, but I would like to know what other open source projects are using. I found a list of the &#8220;Top 20 Most Commonly Used Licenses in Open Source Projects&#8221; (<a href="http://www.blackducksoftware.com/oss/licenses">http://www.blackducksoftware.com/oss/licenses</a>). With the comparisons and the ranking I am leaning towards the GNU General Public License (GPL) and the GNU Lesser General Public License (LGPL).</p>
<p>I went to &#8216;gnu.org&#8217; to research these licenses and I stumbled across a page called <a href="http://www.gnu.org/licenses/why-not-lgpl.html">Why you shouldn&#8217;t use the Lesser GPL for your next library</a>.  It says, &#8220;The choice of license makes a big difference: using the Lesser GPL permits use of the library in proprietary programs; using the ordinary GPL for a library makes it available only for free programs.&#8221;  In my mind this is a reason to use the &#8220;Lesser&#8221; license.  I want to provide an open source project that can be used in any product.  The &#8220;Lesser&#8221; license provides more to the community.   In all fairness it is worth mentioning that the ordinary GPL is designed to encourage developers to open source the software that uses these libraries.  In my case I want to make my library available to anyone.</p>
<p>Now that I have decided on the license I am going to put the following disclaimer at the top of every file:</p>
<blockquote><p>Copyright (c) 2011 Source Allies</p>
<p>This library is free software; you can redistribute it and/or<br />
modify it under the terms of the GNU Lesser General Public<br />
License as published by the Free Software Foundation;<br />
version 3.0.</p>
<p>This library is distributed in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU<br />
Lesser General Public License for more details.</p>
<p>You should have received a copy of the GNU Lesser General Public<br />
License along with this library; if not, visit<br />
<a href="http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt</a>.</p></blockquote>
<p>I also need to include a license.txt file at the root of my project that contains the full text of the <a href="http://www.gnu.org/licenses/lgpl.txt">LGPL</a>.</p>
<p>Make sure you get the license in place before you start distributing or using the jar with third party organizations.  In the case of consulting the client may end up owning the product if it is not licensed properly.  Why go to so much trouble to open source code just to have the right lost to a third party organization?</p>
<h2>Setup GitHub</h2>
<p>I already have a GitHub account, but I want to setup an organization to manage a team of developers.  I am able to create an organization under my personal &#8216;Account Settings&#8217; under &#8216;Organizations&#8217;.  I clicked the &#8216;Create Organization&#8217; button and followed the wizard.  For more information visit <a href="https://github.com/blog/674-introducing-organizations">https://github.com/blog/674-introducing-organizations</a>.</p>
<h2>Collaboration</h2>
<p>I am curious how open source projects manage changes from non-committers.  I found a great article at GitHub that explains how most teams collaborate within their site (<a href="http://help.github.com/pull-requests">http://help.github.com/pull-requests</a>).  In short, contributors outside of the core development team submit &#8220;Pull Requests&#8221;.  The project administrator(s) review these requests and decide if they want to merge them back into the code base.  In my experience Git merging is fairly painless.  This model allows anyone in the world the opportunity to contribute, while preserving the owners right to control the flow of changes.  Too many chefs in the kitchen will ruin the food.</p>
<h2>U-turn</h2>
<p>I started looking for &#8220;How To&#8221; open source software articles and books.   I didn&#8217;t find very many resources.  Everyone talks about how to use  open source, but very few people talk about how to effectively open  source your own software.  Eventually I ran accross &#8220;Producing Open  Source Software: How to Run a Successful Free Software Project&#8221; by Karl  Fogel (<a href="http://producingoss.com/producingoss.pdf">http://producingoss.com/producingoss.pdf</a>).  This book is a collection of insights from a major contributor to the open source project Subersion (<a href="http://subversion.apache.org/">http://subversion.apache.org</a>).   I gravitated to this book because it is free.  Apparently Karl believes  software and books should be available at no charge .</p>
<p>In the  first chapter Fogel suggestes that 90 to 95% of all open source projects  fail.  As the founding committer of Subversion, Karl has a little bit of  experience leading a wildly successful open source project.  &#8220;This book  is about avoiding failure. It examines not only how to do things right,  but how to do them wrong, so you can recognize and correct problems  early.&#8221; (p. 10)  So it is time to look at my mistakes so far.</p>
<p>First,  I have not selected a &#8220;good name&#8221; (p. 21-22).  So what does &#8220;good&#8221;  mean.  The project names that I talk about are the ones that I  remember.  I am drawn to word plays like Mockito (mockito.org) which is a  play on the drink Mojito.  When I heard it I remembered two  things, the punny name and it&#8217;s purpose of mocking.</p>
<p>Second, I  need to develop a &#8220;clear mission&#8221; (p. 22 &#8211; 23).  I have to admit that  this idea of a mission statement is overwhelming to me.  In order to put  myself to sleep I googled a few corporate mission statements.  Without  referring back to their statements I would not be able to tell you what  they were.  Ultimately they stated that they were super awesome  organizations focused on making money.  Nevertheless, what is a good and  useful mission statement?  Karl describes it as a &#8220;quick description&#8221;.   A statement that helps the customer decide in 30 seconds if they are  interested in your project.  He recommends that this statement be  &#8220;prominently placed on the front  page, preferably right under the project&#8217;s name.&#8221; (p.22)  If we take a  look at Mockito again they  state, right under their name, that it is  &#8220;simpler &amp; better mocking&#8221;  (mockito.org).  Traditionally I would consider this a tagline and not a  mission statement.  Nevertheless, I know several company&#8217;s taglines  but I don&#8217;t know a single &#8220;mission statement&#8221;.  So what the heck, why  split hairs?</p>
<p>While it seems strange, the third thing is to &#8220;state that the  project is free&#8221;. (p. 22-23).  I had to visit several open source  project homepages to find an example of this.  I did find the  phrase &#8220;open source&#8217; in the first two sentences at  http://subversion.apache.org.  This does not seem to be a common  practice, but it doesn&#8217;t take much effort to put the words &#8220;open  source&#8221; in the description of the project.</p>
<p>Fourth, I need to take  time to create clear documentation (p. 26-29).  This just takes time.   The obvious first step is a Getting Started page.   What&#8217;s more difficult is writing this  from the perspective of someone that knows nothing about my product.  Fogel suggests that you do not have to wait until you have comprehensive documentation.  On the other hand, just write down some basic information.  It does not matter if it is incomplete.  Focus on helping new users get your product running.</p>
<h2>New Direction</h2>
<p>After reading this I need to slow down and make sure that we put our best foot forward.  We need a good name, logo, and well designed website.  I need to clearly state what this software does.   I need to put  together some basic documentation that is easy to read and understand.</p>
<p>After some discussion we decided to setup a logo contest on <a href="https://99designs.com/">https://99designs.com</a>.   This was very easy to setup and we got some amazing designs.  I also  went through every class and added javadocs.  I put together some  short screen casts with Camtasia (<a href="http://www.techsmith.com/camtasia/">http://www.techsmith.com/camtasia/</a>).   This took a few tries, but the results were well worth it.  Now I&#8217;m  working on integrating all of this documentation into an intuitive and  effective website design.</p>
<p>As a software developer it is easy for  me to focus on the technical aspects of my software and neglect the  presentation.  While this may not be my initial focus I  found that as a consumer I evaluate other projects in a few seconds  based on how their websites looks.  If I feel like it is interesting I  start click through their site.  If I don&#8217;t &#8220;get it&#8221; in a few clicks I  move on.  This evaluation period is extended if I have a recommendation  from a friend or colleague.  Nevertheless, I make snap judgments on  aesthetics, not on the substance of the project.</p>
<p>If I know this  about myself, then I need to make a reasonable investment in the initial  presentation of this software.   Even though our project will be  distributed freely, we decided to spend money on the design to make sure  our presentation matches the quality of our software.  Unfortunately it costs money to provide a quality open source product.</p>
<h2>Conclusions</h2>
<p>I  have to admit that I have been avoiding this journey for quite a  while.  Between the licensing and the project administration I felt a  bit overwhelmed.  Nevertheless, I am starting with a small pilot project  that has focused and limited functionality.  I&#8217;m sure that there will  be a lessons learned blog that will emerge out of this experience as  time goes on.  Until then have fun sharing your code with the world and check out Source Allies newest open source project at <a href="http://beanoh.org">beanoh.org</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/07/creating-an-open-source-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maven 3 Tutorial &#8211; Project Setup</title>
		<link>http://blogs.sourceallies.com/2011/06/maven-3-tutorial-project-setup/</link>
		<comments>http://blogs.sourceallies.com/2011/06/maven-3-tutorial-project-setup/#comments</comments>
		<pubDate>Sat, 11 Jun 2011 22:27:52 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Aggregate POM]]></category>
		<category><![CDATA[Dependency Management]]></category>
		<category><![CDATA[M3_HOME]]></category>
		<category><![CDATA[Maven 3]]></category>
		<category><![CDATA[Maven3]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[POM]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2179</guid>
		<description><![CDATA[
Overview

What is Maven?
Plugins
Why not Ant and Ivy?
But It Downloads the Internet


Getting Started

Install
What is a POM?
Convention over Configuration
New Project


Project Management

Parent POM
Local Maven Repository
Multiple Artifacts from a Single Source
Release Plugin
Aggregate POM
Dependency Management
Distribution Zip


Conclusions

Overview
What is Maven?
Maven is a software project management and comprehension tool that includes: build tools, dependency management, project reporting and much more.  I say &#8220;much [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li><strong>Overview</strong>
<ul>
<li>What is Maven?</li>
<li>Plugins</li>
<li>Why not Ant and Ivy?</li>
<li>But It Downloads the Internet</li>
</ul>
</li>
<li><strong>Getting Started</strong>
<ul>
<li>Install</li>
<li>What is a POM?</li>
<li>Convention over Configuration</li>
<li>New Project</li>
</ul>
</li>
<li><strong>Project Management</strong>
<ul>
<li>Parent POM</li>
<li>Local Maven Repository</li>
<li>Multiple Artifacts from a Single Source</li>
<li>Release Plugin</li>
<li>Aggregate POM</li>
<li>Dependency Management</li>
<li>Distribution Zip</li>
</ul>
</li>
<li><strong>Conclusions</strong></li>
</ul>
<h1>Overview</h1>
<h2>What is Maven?</h2>
<p>Maven is a software project management and comprehension tool that includes: build tools, dependency management, project reporting and much more.  I say &#8220;much more&#8221; because at the core Maven is a plugin execution framework.  There are plugins supported by the Maven project (http://maven.apache.org/plugins/index.html), plugins supported by Mojo Project (http://mojo.codehaus.org/plugins.html), and third party plugins.  If you can find or write a plugin, Maven can run it.<br />
<span id="more-2179"></span></p>
<h2>Plugins</h2>
<p>Plugins are configured to run during specific phases in the Maven lifecycle.  The high-level phases that make up the build lifecycle include: validation, compile, test, package, integration-test, verify, install, and deploy.  An exhaustive list of build phases can be found at <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference.">http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference.</a></p>
<h2>Why not Ant and Ivy?</h2>
<p>People always gravitate to this question of whether Maven is better than Ant and Ivy.  Unfortunately this is not a fare comparison.  Ant is a build tool and Ivy is a dependency management tool.  Maven is not just a build tool or just a dependency management tool.  On the contrary, Maven is a project management tool that embodies software development best practices.</p>
<p>To illustrate this point I will share a story from my early years in software development.  Our shop used Ant without Ivy.  Ivy didn&#8217;t become a full fledged Apache project until October, 2007.  Each team had their own Ant build.  As we began to move from team to team we had to find out which targets needed to be run.  Over time we decided on a set of names that every team needed to implement.  This helped but just because the target was named the same thing it did not mean they worked the same way.</p>
<p>Long story short, we began to meet to create a shared standard.  During this long process we were introduced to Maven.  Ironically, Maven had accepted standards for many of the issues that we were trying address.  Maven was not just a standard for our company it was a standard for all Maven users.  New employees that were familiar with Maven had a good grasp of how we managed our projects.</p>
<p>Maven provided a standard that not only addressed our concerns as software developers.  It provided a standard solution that supported our corporate: audits, disaster recovery, tracability, and the list goes on.  We were trying to reinvent the wheel with Ant when the Maven community had already solved these problems.</p>
<p>Ant and Ivy are powerful ingredients for designing a custom build process.  Maven however is a powerful solution for building and managing software.  In our case we wanted a solution instead of the ingredients and tools to create our own solution.  Maven satisfied our needs and saved us significant time and money.</p>
<h2>But It Downloads the Internet</h2>
<p>I can&#8217;t tell you how many people have told me that they don&#8217;t like Maven because it &#8220;downloads the internet&#8221;. I find it ironic that many of them like Ivy.  I hate to break the news, but Ivy downloads the internet too. I&#8217;m not sure why this is a concern.  Is there a fear that Maven will fill up their hard drive?  Disk space is cheap.  The computer I am working on right now has 150GB of hard disk space and my Maven local repository is eating up 300MB of it.  This computer has pleanty of room for more of the internet.</p>
<p>I recall the first time that I tried to setup a new project without a dependency management tool.  I spent over a week trying to download the correct version of each JAR.  I was ready to take a vacation by the time I finished this ugly puzzle.  After using Maven and Ivy for managing my  dependencies I will never go back.  By the time I downloaded all the JARs that we needed, I felt like I had in fact downloaded the entire internet.</p>
<p>I love dependency management tools and they can have as much of my hard drive as they need.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/06/maven-3-tutorial-project-setup/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Testing Spring Wiring</title>
		<link>http://blogs.sourceallies.com/2011/06/testing-spring-wiring/</link>
		<comments>http://blogs.sourceallies.com/2011/06/testing-spring-wiring/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 17:00:20 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2045</guid>
		<description><![CDATA[Overview
Spring is an essential part of my technology stack.  I cann&#8217;t image providing quality software that doesn&#8217;t leverage an IoC container.  However, decoupling components requires some amount of configuration.  Whether this is accomplished through annotations or XML, it&#8217;s fairly easy to mess up.  Fixing these missing or incorrect configurations doesn&#8217;t take [...]]]></description>
			<content:encoded><![CDATA[<h1>Overview</h1>
<p><a href="http://en.wikipedia.org/wiki/Spring_Framework" target="_blank">Spring</a> is an essential part of my technology stack.  I cann&#8217;t image providing quality software that doesn&#8217;t leverage an <a href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank">IoC</a> container.  However, decoupling components requires some amount of configuration.  Whether this is accomplished through annotations or XML, it&#8217;s fairly easy to mess up.  Fixing these missing or incorrect configurations doesn&#8217;t take very long.  The real question is how quickly can you identify these errors?</p>
<p>This question of how long, is a feedback loop question.  Unfortunately many teams wait until they fire up the application server to see if their Spring context is wired correctly.  This is too late.</p>
<p>One of our clients suffered from this very issue.  Due to environmental constraints they could not run automated, in-container tests that would have identified misconfigured beans.  After repeatedly committing stupid configuration mistakes, I decided that I would write a Spring wiring test.  As I began to write this I encountered five problems.<br />
<span id="more-2045"></span></p>
<h1>Problem 1: Scope</h1>
<p>The first problem that I encountered was that not all of my beans were being created when I loaded my context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@RunWith<span style="color: #009900;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
@ContextConfiguration
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SpringWiringTest<span style="color: #009900;">&#123;</span>
&nbsp;
     @Test
     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSomething<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
...</pre></div></div>

<p>I quickly remembered that only beans with the default &#8217;singleton&#8217; scope will be loaded immediately.  The rest of the bean scopes (&#8217;prototype&#8217;, &#8216;request&#8217;, and &#8217;session&#8217;) will not be created until they are requested.  In order to solve this I looped through all of the bean names and retrieved each bean from the context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> names <span style="color: #339933;">=</span> context.<span style="color: #006633;">getBeanDefinitionNames</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name <span style="color: #339933;">:</span> names<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
     context.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>However, when I ran this I got the following error</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">java.<span style="color: #006633;">lang</span>.<span style="color: #003399;">IllegalStateException</span><span style="color: #339933;">:</span> No Scope registered <span style="color: #000000; font-weight: bold;">for</span> scope <span style="color: #0000ff;">'request'</span></pre></div></div>

<p>In order to correct this issue I added the following setup method.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Before
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testCaseSetUp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
     context.<span style="color: #006633;">getBeanFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">registerScope</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;session&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> SessionScope<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     context.<span style="color: #006633;">getBeanFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">registerScope</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;request&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> RequestScope<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     MockHttpServletRequest request <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MockHttpServletRequest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     ServletRequestAttributes attributes <span style="color: #339933;">=</span>
          <span style="color: #000000; font-weight: bold;">new</span> ServletRequestAttributes<span style="color: #009900;">&#40;</span>request<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     RequestContextHolder.<span style="color: #006633;">setRequestAttributes</span><span style="color: #009900;">&#40;</span>attributes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I threw in the session scope too just to be safe.</p>
<h1>Problem 2: Abstract Bean Definitions</h1>
<p>The second problem that I had to solve was requesting abstract beans.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">BeanIsAbstractException</span><span style="color: #339933;">:</span> <span style="color: #003399;">Error</span> creating bean
with name <span style="color: #0000ff;">'testBean'</span><span style="color: #339933;">:</span> Bean definition is <span style="color: #000000; font-weight: bold;">abstract</span></pre></div></div>

<p>In order to solve this issue I added a check to verify if a bean definition was abstract.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> names <span style="color: #339933;">=</span> context.<span style="color: #006633;">getBeanDefinitionNames</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name <span style="color: #339933;">:</span> names<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
     BeanDefinition beanDefinition <span style="color: #339933;">=</span> context.<span style="color: #006633;">getBeanDefinition</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>beanDefinition.<span style="color: #006633;">isAbstract</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          context.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h1>Problem 3: Mock Beans</h1>
<p>The third issue I found was environment specific beans.  JNDI references are one type of environment specific bean.</p>
<blockquote><p><code>&lt;jee:jndi-lookup id="testBean" jndi-name="jdbc/test"/&gt;</code></p></blockquote>
<p>In order to solve this issue, I decided to create a test bootstrap context that imported all of the production contexts.  This provided a place for me to override beans that I wanted to create for the test.  I used Mockito to create mock beans in most situations.</p>
<blockquote><p><code>&lt;bean id="testBean" class="org.mockito.Mockito" factory-method="mock"&gt;<br />
&lt;constructor-arg value="com.something.Foo" /&gt;<br />
&lt;/bean&gt;</code></p></blockquote>
<p>While this worked for most beans, I received errors when I wired up mock DataSources.  Instead I used embedded databases to replace real DataSources.</p>
<blockquote><p><code>&lt;bean id="testDataSource"<br />
class="org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean"<br />
p:databaseType="H2"<br />
abstract="true"/&gt;</code></p></blockquote>
<h1>Problem 4: Components</h1>
<p>This fourth issue was harder to identify but equally problematic.  I frequently wired up beans with the @Component annotation and failed to configure an &#8216;component-scan&#8217; for those packages.</p>
<blockquote><p><code>&lt;context:component-scan base-package="com.sourceallies"/&gt;</code></p></blockquote>
<p>In other words I needed to reconcile the classes marked with the @Component annotation with the beans that were available in the Spring context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">ClassPathScanningCandidateComponentProvider scanner <span style="color: #339933;">=</span>
     <span style="color: #000000; font-weight: bold;">new</span> ClassPathScanningCandidateComponentProvider<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
scanner.<span style="color: #006633;">addIncludeFilter</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AnnotationTypeFilter<span style="color: #009900;">&#40;</span><span style="color: #003399;">Component</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>BeanDefinition bean <span style="color: #339933;">:</span> scanner.<span style="color: #006633;">findCandidateComponents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;com.something&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      components.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>bean.<span style="color: #006633;">getBeanClassName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This will create a list of components found on the classpath under the specified base package.  Reconciling this list with the beans loaded in the Spring context will identify any components that are not configured in Spring.  This list came in handy for two reasons.  First it identified any components that I needed to configure in Spring.  Second it listed components that were provided in dependent jars.  This list helped us become proactive instead of reactive.</p>
<h1>Problem 5: Duplicate Bean Definitions</h1>
<p>The fifth issue is duplicate bean definitions.  This can occur when more than one bean has the same bean definition name.  This can also occur when the same context is loaded multiple times.  By default Spring allows the new bean definition to overwrite the previous one.  This sounds annoying but harmless.  On the contrary, Spring does not guarantee the loading order.  Furthermore, each deployment environment&#8217;s classloader can load context files in a different order.  The bottom line is that duplicate bean definitions can result in subtle and painful bugs.</p>
<p>While this issue was clear to me the solution was a bit more illusive.  At first I tried to set the allowBeanDefinitionOverriding flag on org.springframework.beans.factory.support.DefaultListableBeanFactory.  This throws an exception if the same bean definition is loaded multiple times.  Case closed, right?</p>
<p>Unfortunately the solution was not this simple.  Problem 3, Mock Beans, requires the creation of a test bootstrap context that overrides bean definitions.  So the allowBeanDefinitionOverriding flag is out.  After crying a little, I started exploring Spring.  Long story short, I overrode the  &#8216;protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)&#8217; method on org.springframework.context.support.ClassPathXmlApplicationContext and injected a delegating proxy.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> loadBeanDefinitions<span style="color: #009900;">&#40;</span>DefaultListableBeanFactory beanFactory<span style="color: #009900;">&#41;</span>
		<span style="color: #000000; font-weight: bold;">throws</span> BeansException, <span style="color: #003399;">IOException</span> <span style="color: #009900;">&#123;</span>
	Enhancer enhancer <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Enhancer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	enhancer.<span style="color: #006633;">setSuperclass</span><span style="color: #009900;">&#40;</span>DefaultListableBeanFactory.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	BeanohBeanFactoryMethodInterceptor callback <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BeanohBeanFactoryMethodInterceptor<span style="color: #009900;">&#40;</span>
			beanFactory<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	callbacks.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	enhancer.<span style="color: #006633;">setCallback</span><span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	DefaultListableBeanFactory proxy <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>DefaultListableBeanFactory<span style="color: #009900;">&#41;</span> enhancer
			.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">loadBeanDefinitions</span><span style="color: #009900;">&#40;</span>proxy<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I used &#8216;net.sf.cglib.proxy.Enhancer&#8217; and &#8216;net.sf.cglib.proxy.MethodInterceptor&#8217; to create a proxy.  The trick was to delegate to the real &#8216;org.springframework.beans.factory.support.DefaultListableBeanFactory&#8217; instance.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> intercept<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> object, <span style="color: #003399;">Method</span> method, <span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args,
		MethodProxy methodProxy<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Throwable</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #003399;">Method</span> delegateMethod <span style="color: #339933;">=</span> delegateClass.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span>method.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>,
			method.<span style="color: #006633;">getParameterTypes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;registerBeanDefinition&quot;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>method.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>beanDefinitionMap.<span style="color: #006633;">containsKey</span><span style="color: #009900;">&#40;</span>args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">List</span> definitions <span style="color: #339933;">=</span> beanDefinitionMap
					.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			definitions.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>BeanDefinition<span style="color: #009900;">&#41;</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">List</span> beanDefinitions <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ArrayList</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			beanDefinitions.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>BeanDefinition<span style="color: #009900;">&#41;</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			beanDefinitionMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span>, beanDefinitions<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">return</span> delegateMethod.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>delegate, args<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This passively collects bean definitions that are registered with the registerBeanDefinition method.  This method takes two arguments: a String bean name (arg[0]) and a &#8216;org.springframework.beans.factory.config.BeanDefinition&#8217; (arg[1]).  This map of bean definitions can be inspected later to determine if beans were loaded multiple times.</p>
<h1>Conclusions</h1>
<p>This experience has lead our team to develop a complete, open source solution called <a href="http://beanoh.org">Beanoh</a> (pronounced \&#8217;beanˌō\).  Simply <a href="http://search.maven.org/remotecontent?filepath=com/sourceallies/beanoh/beanoh/1.0.0/beanoh-1.0.0.jar">download</a> the jar or build the project with maven and start using it.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SomeTest <span style="color: #000000; font-weight: bold;">extends</span> BeanohTestCase <span style="color: #009900;">&#123;</span>
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSomething<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		assertContextLoading<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>For more information visit <a href="http://beanoh.org/overview.html">http://beanoh.org/overview.html</a>.</p>
<p>In just a few short weeks this testing approach prevented our team from committing broken Spring configurations.  Furthermore, we took time to evaluate the inherited components that we received through our project dependencies.  This provided valuable insights into our dependency structure and our packaging strategy.</p>
<p>These wiring tests even gave us feedback as we refactored our spring contexts.  We were able to simplify our context files without worrying that we would break something.  We also identified unused and duplicate bean definitions.  Without the quick feedback of this wiring test we would have committed broken changes that effected the whole team.</p>
<p>Automated tests help you manage code behavior rather than allowing code to drive your behavior.  <a href="http://beanoh.org">Download Beanoh</a> today and take control of your Spring configuration.</p>
<p>For more information checkout our YouTube <a href=" http://www.youtube.com/playlist?p=PL7F1B7F11D0D0FB91">video tutorials</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/06/testing-spring-wiring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mock Me With Fewer Words</title>
		<link>http://blogs.sourceallies.com/2011/05/mock-me-with-fewer-words/</link>
		<comments>http://blogs.sourceallies.com/2011/05/mock-me-with-fewer-words/#comments</comments>
		<pubDate>Sun, 01 May 2011 10:00:20 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2032</guid>
		<description><![CDATA[With Mockito 1.8.3 or higher you can significantly reduce your test code setup.

Here is the code before.

public class MockitoTest &#123;
&#160;
   private EmailFactory emailFactory;
   private Notifier notifier;
   private Emailer emailer;
   private Email email;
&#160;
   @Before
   public void setUp&#40;&#41;&#123;
      notifier = [...]]]></description>
			<content:encoded><![CDATA[<p>With <a href="http://code.google.com/p/mockito/" target="_blank">Mockito</a> 1.8.3 or higher you can significantly reduce your test code setup.<br />
<span id="more-2032"></span><br />
Here is the code before.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MockitoTest <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> EmailFactory emailFactory<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> Notifier notifier<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> Emailer emailer<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> Email email<span style="color: #339933;">;</span>
&nbsp;
   @Before
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setUp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      notifier <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Notifier<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      emailFactory <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span>EmailFactory.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      emailer <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span>Emailer.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      email <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span>Email.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      notifier.<span style="color: #006633;">setEmailFactory</span><span style="color: #009900;">&#40;</span>emailFactory<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      notifier.<span style="color: #006633;">setEmailer</span><span style="color: #009900;">&#40;</span>emailer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @Test
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSend<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      when<span style="color: #009900;">&#40;</span>emailFactory.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">thenReturn</span><span style="color: #009900;">&#40;</span>email<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      notifier.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      verify<span style="color: #009900;">&#40;</span>emailFactory<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      verify<span style="color: #009900;">&#40;</span>emailer<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span>email<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      verifyNoMoreInteractions<span style="color: #009900;">&#40;</span>emailFactory<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      verifyNoMoreInteractions<span style="color: #009900;">&#40;</span>emailer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Notifier<span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">private</span> EmailFactory emailFactory<span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">private</span> Emailer emailer<span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> send<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
         Email email <span style="color: #339933;">=</span> emailFactory.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         emailer.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span>email<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setEmailer<span style="color: #009900;">&#40;</span>Emailer emailer<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">emailer</span> <span style="color: #339933;">=</span> emailer<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setEmailFactory<span style="color: #009900;">&#40;</span>EmailFactory emailFactory<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">emailFactory</span> <span style="color: #339933;">=</span> emailFactory<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here is the code using the new annotations.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@RunWith<span style="color: #009900;">&#40;</span>MockitoJUnitRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MockitoAnnotationsTest <span style="color: #009900;">&#123;</span>
&nbsp;
   @Mock <span style="color: #000000; font-weight: bold;">private</span> EmailFactory emailFactory<span style="color: #339933;">;</span>
   @Mock <span style="color: #000000; font-weight: bold;">private</span> Emailer emailer<span style="color: #339933;">;</span>
   @Mock <span style="color: #000000; font-weight: bold;">private</span> Email email<span style="color: #339933;">;</span>
   @InjectMocks <span style="color: #000000; font-weight: bold;">private</span> Notifier notifier <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Notifier<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   @Test
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSend<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      when<span style="color: #009900;">&#40;</span>emailFactory.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">thenReturn</span><span style="color: #009900;">&#40;</span>email<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      notifier.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      verify<span style="color: #009900;">&#40;</span>emailFactory<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      verify<span style="color: #009900;">&#40;</span>emailer<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span>email<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      verifyNoMoreInteractions<span style="color: #009900;">&#40;</span>emailFactory<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      verifyNoMoreInteractions<span style="color: #009900;">&#40;</span>emailer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Notifier<span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">private</span> EmailFactory emailFactory<span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">private</span> Emailer emailer<span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> send<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
         Email email <span style="color: #339933;">=</span> emailFactory.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         emailer.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span>email<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span></pre></div></div>

<p>This new annotation style reduced the number of lines of code by over 40%.  The longer a test is the harder it is to understand.  Reducing the amount of test code increases its clarity.</p>
<p>So how does it work?  &#8216;@Mock&#8217; is equivalent &#8216;Mockito.mock(Some.class)&#8217;.  &#8216;@InjectMocks&#8217; is equivalent to setting the mocks on the class under test.  This annotation uses reflection to set properties so you do not have to add setters just for testing.  Lastly, the combination of &#8216;@RunWith(MockitoJUnitRunner.class)&#8217; and &#8216;@InjectMocks&#8217; enables you to remove the &#8216;@Before&#8217; method.  This pair of annotations prepares the class under test before each test method.</p>
<p>I have been using mocks in tests for years and this is a great addition to this powerful framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/05/mock-me-with-fewer-words/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

