<?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>Basil Vandegriend: Professional Software Development &#187; Java</title>
	<atom:link href="http://www.basilv.com/psd/blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.basilv.com/psd</link>
	<description></description>
	<lastBuildDate>Wed, 25 Jan 2012 13:23:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Java Code Examples Available</title>
		<link>http://www.basilv.com/psd/blog/2009/java-code-examples-available</link>
		<comments>http://www.basilv.com/psd/blog/2009/java-code-examples-available#comments</comments>
		<pubDate>Mon, 11 May 2009 16:07:21 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[website]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/?p=382</guid>
		<description><![CDATA[I have added a new project called Java Examples to my Software page. This project contains the source code used as examples in the following articles: Working with Java 5 Annotations Parsing and Generating XML with Java Advanced Uses of Java 5 Enums A Tale of Bad Exception Handling in Finally Blocks in Java Automatically [...]]]></description>
			<content:encoded><![CDATA[<p>I have added a new project called <em>Java Examples</em> to my <a href="http://www.basilv.com/psd/software">Software</a> page. This project contains the source code used as examples in the following articles:</p>
<ul>
<li><a href="http://www.basilv.com/psd/blog/2008/working-with-java-5-annotations">Working with Java 5 Annotations</a></li>
<li><a href="http://www.basilv.com/psd/blog/2006/parsing-and-generating-xml-with-java">Parsing and Generating XML with Java</a></li>
<li><a href="http://www.basilv.com/psd/blog/2006/advanced-uses-of-java-5-enums">Advanced Uses of Java 5 Enums</a></li>
<li><a href="http://www.basilv.com/psd/blog/2007/a-tale-of-bad-exception-handling-in-finally-blocks-in-java">A Tale of Bad Exception Handling in Finally Blocks in Java</a></li>
<li><a href="http://www.basilv.com/psd/blog/2008/automatically-populating-audit-columns-in-hibernate">Automatically Populating Audit Columns in Hibernate</a></li>
<li><a href="http://www.basilv.com/psd/blog/2008/simple-xml-parsing-using-jaxb">Simple XML Parsing using JAXB</a></li>
<li><a href="http://www.basilv.com/psd/blog/2006/tips-for-using-log4j">Tips for Using Log4j</a></li>
<li><a href="http://www.basilv.com/psd/blog/2008/exposing-mutable-objects-as-public-properties">Exposing Mutable Objects as Public Properties</a></li>
<li><a href="http://www.basilv.com/psd/blog/2006/java-rmi-tutorial">Understanding Java RMI: A Simple Tutorial</a></li>
<li><a href="http://www.basilv.com/psd/blog/2009/java-based-configuration-of-spring">Java-Based Configuration of Spring Dependency Injection</a></li>
</ul>
<p>Code is formatted using a non-standard coding convention to display better on the website. Code is generally written with minimal comments or error-handling: it is intended for educational purposes and not necessarily for production use.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2009/java-code-examples-available/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java-Based Configuration of Spring Dependency Injection</title>
		<link>http://www.basilv.com/psd/blog/2009/java-based-configuration-of-spring-dependency-injection</link>
		<comments>http://www.basilv.com/psd/blog/2009/java-based-configuration-of-spring-dependency-injection#comments</comments>
		<pubDate>Fri, 01 May 2009 12:55:15 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/?p=353</guid>
		<description><![CDATA[At the heart of the Spring Framework is its dependency injection capabilities provided by its inversion-of-control container. Traditionally the configuration of dependencies has been done in one or more separate XML files. In these files you need to specify code-specific constructs such as the concrete classes to use as implementations of interfaces. It has always [...]]]></description>
			<content:encoded><![CDATA[<p>At the heart of the <a href="http://www.springsource.org/">Spring Framework</a> is its <a href="http://martinfowler.com/articles/injection.html">dependency injection</a> capabilities provided by its inversion-of-control container. Traditionally the configuration of dependencies has been done in one or more separate XML files. In these files you need to specify code-specific constructs such as the concrete classes to use as implementations of interfaces. It has always seemed unnatural to me to do this configuration within XML instead of using Java code. One problem, for example, is that doing renames of your classes or packages will break your XML configuration. Tooling support for these Spring XML files has admittedly helped, but doesn't overcome for me the fundamental inconsistency in using XML to configure Java code. What's wrong with using Java? Traditionally, one significant problem with doing Spring configuration within Java code is that it turned out to be much more verbose than the XML files – the Spring Java APIs were not explicitly designed and optimized to do Java-based configuration. </p>
<p>This state of affairs with Spring configuration changed with the introduction of the <a href="http://www.springsource.org/javaconfig">Spring Java Configuration project</a>, commonly called JavaConfig. JavaConfig provides roughly the same capabilities as Spring's XML-based configuration but uses Java code that is quite compact and readable. I have tried out JavaConfig and I really like it – my unease over XML configuration has been finally laid to rest. Using JavaConfig is fairly simple: you create one or more configuration classes using the conventions expected by JavaConfig, then create an instance of <code>JavaConfigApplicationContext</code> or <code>JavaConfigWebApplicationContext</code> and use it like a regular Spring <code>AppplicationContext</code>.</p>
<p>The most significant decision I think you need to make when using JavaConfig is what approach to use to define dependencies. The approach you choose determines how you go about writing your configuration class. While this decision is not specific to JavaConfig - Spring's standard XML configuration allows for the same set of approaches to be used – the application of each approach using JavaConfig is different. These three approaches to defining dependencies are:</p>
<ol>
<li>Explicit declaration of beans and dependencies.</li>
<li>Automatic dependencies via autowiring.</li>
<li>Automatic beans via component scanning.</li>
</ol>
<p>In the remainder of this article I am going to provide examples using JavaConfig for these three approaches and discuss the pros and cons of each. While the examples focus exclusively on one of the approaches at a time you can easily combine all three approaches within a single configuration class. For the sake of clarity, however, I recommend on real projects to choose one approach as the primary method of configuration. The source code listed in this article is provided in the <em>Java Examples</em> project which can be downloaded from the <a href="http://www.basilv.com/psd/software">Software</a> page.</p>
<p>All three approaches use the same configuration example. There are two beans to configure, each with an interface and an underlying implementation class. The first bean is <code>ResumeRepository</code> which is a Repository class (aka Data Access Object) that provides CRUD-type operations for the domain object <code>Resume</code>. For this example this repository interface only contains a single method <code>Set&lt;Resume&gt; findAll()</code>. The second bean is <code>CalculatorService</code>, which is a Service class that provides functionality relating to resumes:  for this example a single method <code>void validate(Resume)</code>. The Java code for these two interfaces and the domain object is provided below:</p>
<pre class="prettyprint">
package com.basilv.examples.spring;
import java.util.Set;

public interface CalculatorService
{
  boolean validate(Resume resume);
}

public interface ResumeRepository
{
  Set&lt;Resume&gt; findAll();
}

public class Resume
{
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  private String name;
}
</pre>
<p>The implementation class of <code>CalculatorService</code> is <code>CalculatorServiceImpl</code> which requires (has a dependency on) <code>ResumeRepository</code>. The implementation class of <code>ResumeRepository</code> is <code>HardcodedResumeRepository</code>, which is used for this example rather than a more typical repository implementation to avoid further dependencies on e.g. a DataSource. These implementation classes are the same in terms of logic across the three approaches, but there are configuration differences so the code for these classes will be shown for each approach below.</p>
<h3>Explicit Declaration of Beans and Dependencies</h3>
<p>The explicit approach requires that all beans and their dependencies be explicitly coded within the configuration class as shown below:</p>
<pre class="prettyprint">
package com.basilv.examples.spring.explicit;

import org.springframework.config.java.annotation.*;
import com.basilv.examples.spring.*;

@Configuration
public class ExplicitConfig
{
  @Bean
  public ResumeRepository resumeRepository() {
    return new HardcodedResumeRepository();
  }

  @Bean
  public CalculatorService calculatorService() {
    return new CalculatorServiceImpl(
      resumeRepository()); // Inject dependency
  }
}
</pre>
<p>The <code>@Configuration</code> annotation is needed on the class, and each bean definition method must be annotated with <code>@Bean</code>. By default bean names are based on the method names.</p>
<p>The implementation classes <code>HardcodedResumeRepository</code> and <code>CalculatorServiceImpl</code> do not require any special configuration code. Constructor injection was used in <code>CalculatorServiceImpl</code> as it is safer and results in more compact code within the configuration class. The code for these implementation classes is shown below:</p>
<pre class="prettyprint">
package com.basilv.examples.spring.explicit;

import java.util.*;
import com.basilv.examples.spring.*;

public class HardcodedResumeRepository implements ResumeRepository
{
  public Set&lt;Resume&gt; findAll() {
    HashSet&lt;Resume&gt; set = new HashSet&lt;Resume&gt;();
    Resume resume = new Resume();
    resume.setName("Coded, Hard");
    set.add(resume);

    return set;
  }
}

public class CalculatorServiceImpl implements CalculatorService
{
  private ResumeRepository resumeRepository;

  public CalculatorServiceImpl(ResumeRepository resumeRepository) {
    this.resumeRepository = resumeRepository;
  }

  public boolean validate(Resume resume) {
      for (Resume repoResume : resumeRepository.findAll()) {
        if (repoResume.getName().equals(resume.getName())) {
          return true;
        }
      }

      return false;
  }
}
</pre>
<p>As explained above, using the <code>ExplicitConfig</code> configuration class is quite simple. The unit test shown below demonstrates how it is done.</p>
<pre class="prettyprint">
package com.basilv.examples.spring.explicit;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.Set;

import org.junit.*;
import org.springframework.config.java.context.JavaConfigApplicationContext;

import com.basilv.examples.spring.*;

public class ExplicitConfigTest
{
  private JavaConfigApplicationContext context;

  @Before
  public void setUp() {
    context = new JavaConfigApplicationContext(ExplicitConfig.class);
  }

  @Test
  public void repositoryConfig() {

    ResumeRepository resumeRepository = context.getBean(ResumeRepository.class);
    Set&lt;Resume&gt; resumes = resumeRepository.findAll();
    assertNotNull(resumes);
    assertTrue(!resumes.isEmpty());
  }

  @Test
  public void serviceConfig() {

    CalculatorService service = context.getBean(CalculatorService.class);
    assertNotNull(service);

    assertFalse(service.validate(new Resume()));
  }

}
</pre>
<p>One nice feature of the <code>JavaConfigApplicationContext</code> class is that beans can be retrieved  via the <code>getBean</code> method in a type-safe manner with no casting required. The only piece of this code that is specific to this approach is the configuration class used – the other approaches to defining dependencies do not need to change anything else in this test case.</p>
<p>At first glance it may appear that the configuration class with its explicit definitions could be used directly without Spring. That would be correct for this simplistic example. In real-life usage, however, the Spring Framework provides many additional features via its container including bean life-cycle events, bean scope (singleton versus prototype), and aspects such as transactional behavior.</p>
<h3>Automatic Dependencies via Autowiring</h3>
<p>While the explicit declaration approach described above may look quite reasonable for this simplistic example, in real-life usage the number of dependencies per class can really add up, particularly for Service classes that may require five or more Repository or other Service classes. Instead of manually defining all of these dependencies, Spring allows such dependencies to be inferred using a feature called Autowiring.</p>
<p>Here is how Autowiring works. Dependencies within an implementation class must be flagged with the <code>@Autowired</code> annotation. At bean construction time the Spring container will automatically populate these dependencies by finding a matching bean based on the Java type. (Multiple beans of the same type can be handled through the use of qualifiers or through the <code>@Resource</code> annotation. See the Spring documentation for further details.) </p>
<p>While the Spring XML-based configuration can autowire both constructor and setter injection, Java-based configuration cannot autowire dependencies in constructors when beans are explicitly defined. So for the example the <code>CalculatorServiceImpl</code> class had to be changed to use setter injection. Below is the code for the configuration class and <code>CalculatorServiceImpl</code> - the <code>HardcodedResumeRepository</code> class is unchanged from the explicit declaration approach.</p>
<pre class="prettyprint">
package com.basilv.examples.spring.autowire;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.config.java.annotation.*;
import org.springframework.config.java.plugin.context.AnnotationDrivenConfig;
import com.basilv.examples.spring.*;

@Configuration
@AnnotationDrivenConfig // Needed for @Autowire to work
public class AutowireConfig
{

  @Bean
  public ResumeRepository resumeRepository() {
    return new HardcodedResumeRepository();
  }

  @Bean
  public CalculatorService calculatorService() {
    return new CalculatorServiceImpl(); // Do not need to specify dependency.
  }
}

public class CalculatorServiceImpl implements CalculatorService
{
  @Autowired
  private ResumeRepository resumeRepository;

  public boolean validate(Resume resume) {
      for (Resume repoResume : resumeRepository.findAll()) {
        if (repoResume.getName().equals(resume.getName())) {
          return true;
        }
      }

      return false;
  }

  public void setResumeRepository(ResumeRepository resumeRepository) {
    this.resumeRepository = resumeRepository;
  }
}
</pre>
<h3>Automatic Beans via Component Scanning</h3>
<p>While the previous approach did reduce the amount of configuration required, each bean still needed to be explicitly defined within the configuration class. This approach eliminates this requirement by enabling Spring to scan for component classes that are automatically configured as beans with dependencies autowired as per the previous approach. Bean implementation classes must be annotated with the annotation <code>@Component</code> or a specialization of this annotation such as <code>@Service</code> or <code>@Repository</code>. The configuration class is then configured to scan one or more packages for these classes. The code below shows the configuration class and the two implementation classes which were revised to add these annotations. </p>
<pre class="prettyprint">
package com.basilv.examples.spring.componentscan;

import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.plugin.context.*;
import org.springframework.stereotype.*;
import com.basilv.examples.spring.*;

@Configuration
@AnnotationDrivenConfig // Needed for @Autowire to work
@ComponentScan("com.basilv.examples.spring.componentscan")
public class ComponentScanConfig
{
  // No explicit configuration needed
}

@Repository
public class HardcodedResumeRepository implements ResumeRepository
{
  public Set&lt;Resume&gt; findAll() {
    HashSet&lt;Resume&gt; set = new HashSet&lt;Resume&gt;();
    Resume resume = new Resume();
    resume.setName("Coded, Hard");
    set.add(resume);

    return set;
  }
}

@Service
public class CalculatorServiceImpl implements CalculatorService
{
  private ResumeRepository resumeRepository;

  @Autowired
  public CalculatorServiceImpl(ResumeRepository resumeRepository) {
    super();
    this.resumeRepository = resumeRepository;
  }

  public boolean validate(Resume resume) {
      for (Resume repoResume : resumeRepository.findAll()) {
        if (repoResume.getName().equals(resume.getName())) {
          return true;
        }
      }

      return false;
  }
}
</pre>
<p>The most notable thing about this example is that the configuration class is empty – all bean definitions and dependencies have been inferred via annotations. The <code>CalculatorServiceImpl</code> class is also able to use autowired constructor injection, unlike the previous approach, because the class itself is being instantiated by the Spring container rather than explicitly in our configuration class.</p>
<h3>Pros and Cons</h3>
<p>There are advantages and disadvantages to each configuration approach. The explicit declaration approach is the easiest to understand, especially for developers unfamiliar with Spring. But this approach is the most work to set up. The approach of autowiring dependencies while explicitly defining beans strikes I believe a nice balance between these two factors. Implementation classes are still explicitly referenced, which I think is important for developers unfamiliar with Spring as otherwise IDEs will report no uses of such classes within the production code base. But all dependency information can be left out. A significant disadvantage with this approach, however, is that constructor injection cannot be autowired. In general I tend to prefer constructor injection, which makes this approach pointless (as constructor dependencies still need to be explicitly defined). The third approach of using component scanning is the most aggressive in minimizing configuration needed – virtually no setup work is required. But I am concerned that this will be much harder to understand for those developers unfamiliar with Spring as a lot of magic is being performed behind the scenes. </p>
<p>Is there a clear winner? I would say no, which is one reason Spring provides for these various configuration options. While I value the ease-of-understanding provided by the first approach, I strongly dislike writing "boilerplate" code, which much of the dependency configuration is, and this pushes me towards the third approach. As per the comment below from Chris Beams, Lead for the Spring JavaConfig project, his recommendation is to use component scanning and not use the hybrid explicit beans + autowiring approach. He also points out that 'external' dependencies, such as data sources, still require explicit configuration.</p>
<p>Despite the questions over the approach to defining dependencies, I am happy with the use of Spring JavaConfig overall. One issue I encountered using Spring JavaConfig is that it is still in beta – it has not had a final 1.0 release yet. I used JavaConfig 1.0.0.M4, which worked fine with Spring 2.5.6 but does not work with Spring 3.0.M2 due to classpath issues. I discovered on the Spring forums that some portion of the JavaConfig functionality with be included in the Spring 3.0 release due out this summer, but it is unclear what is planned for the remaining functionality. See Chris Beam's comment below for more details.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2009/java-based-configuration-of-spring-dependency-injection/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Simple XML Parsing using JAXB</title>
		<link>http://www.basilv.com/psd/blog/2008/simple-xml-parsing-using-jaxb</link>
		<comments>http://www.basilv.com/psd/blog/2008/simple-xml-parsing-using-jaxb#comments</comments>
		<pubDate>Mon, 08 Dec 2008 23:12:32 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[dom4j]]></category>
		<category><![CDATA[JAXB]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/?p=210</guid>
		<description><![CDATA[I recently needed to parse a XML file using Java for a utility I was writing. A couple of years ago I used dom4j to parse XML (and wrote an article about it). I figured there had to be a more modern approach, similar to how Hibernate 3.0 can map POJOs (plain old Java objects) [...]]]></description>
			<content:encoded><![CDATA[<p>I recently needed to parse a XML file using Java for a utility I was writing. A couple of years ago I used <a href="http://www.dom4j.org/">dom4j</a> to parse XML (and wrote an <a href="http://www.basilv.com/psd/blog/2006/parsing-and-generating-xml-with-java">article</a> about it). I figured there had to be a more modern approach, similar to how <a href="http://www.hibernate.org/">Hibernate 3.0</a> can map POJOs (plain old Java objects) to relational database tables using <a href="http://www.basilv.com/psd/blog/2008/working-with-java-5-annotations">Java annotations</a>. To my surprise, a brief search on-line turned up nothing. I was sure I had heard of this being done, so I continued searching. I finally found an <a href="http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html">article</a>  with a comment by <a href="http://www.blogger.com/profile/06165108938304365215">zaeffi</a> that finally enlightened me. The answer was to use <a href="https://jaxb.dev.java.net/">JAXB 2.0</a>.</p>
<p>I had already looked at JAXB, but was turned off by the apparent requirement to generate the Java classes from a XML Schema definition of the XML format - I already had my Java POJOs and did not want to be bothered to write a schema definition. It turns out that JAXB does support my use case. The online documentation, unfortunately, seems strongly biased towards web services developers who more than likely do start with a schema definition, and possibly even have tooling that hides the use of JAXB entirely. I was also misled by older documentation referring to JAXB version 1, which does not support annotations and generates (from the schema) very ugly code that is difficult to maintain. This was fixed in JAXB version 2, which does support the use of annotations (and incidentally generates much cleaner code).</p>
<p>Using that <a href="http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html">article</a> as inspiration, I wrote a helper class for parsing XML into objects and vice-versa. The code for this helper class is shown below:</p>
<pre class="prettyprint">
// Copyright 2008 by Basil Vandegriend.  All rights reserved.

package com.basilv.examples.jaxb;

import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.*;

import org.w3c.dom.Node;

/**
 * Tools for working with the JAXB (XML Binding) library.
 */
public class XmlBindingTools
{
  /**
   * Parse the XML supplied by the reader into the
   * corresponding tree of Java objects.
   *
   * @param reader Cannot be null. The source of the XML.
   * @param rootElementClass Cannot be null. The type of the
   *        root element.
   * @return the Java object that is the root of the tree,
   *         of type rootElement.
   * @throws JAXBException if an error occurs parsing the
   *         XML.
   */
  @SuppressWarnings("unchecked")
  public static &lt;E extends Object&gt; E parseXML(
    Reader reader, Class&lt;E&gt; rootElementClass)
    throws JAXBException {

    if (rootElementClass == null)
      throw new IllegalArgumentException("rootElementClass is null");
    if (reader == null)
      throw new IllegalArgumentException("reader is null");

    JAXBContext context = JAXBContext.newInstance(rootElementClass);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    CollectingValidationEventHandler handler =
      new CollectingValidationEventHandler();
    unmarshaller.setEventHandler(handler);

    E object = (E) unmarshaller.unmarshal(reader);
    if (!handler.getMessages().isEmpty()) {
      String errorMessage = "XML parse errors:";
      for (String message : handler.getMessages()) {
        errorMessage += "\n" + message;
      }
      throw new JAXBException(errorMessage);
    }

    return object;
  }

  /**
   * Generate XML using the supplied root element as the
   * root of the object tree and write the resulting XML to
   * the specified writer
   *
   * @param rootElement Cannot be null.
   * @param writer Cannot be null.
   * @throws JAXBException
   */
  public static void generateXML(Object rootElement,
    Writer writer) throws JAXBException {

    if (rootElement == null)
      throw new IllegalArgumentException("rootElement is null");
    if (writer == null)
      throw new IllegalArgumentException("writer is null");

    JAXBContext context = JAXBContext.newInstance(rootElement.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(
      Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(rootElement, writer);
  }

  private static class CollectingValidationEventHandler
    implements ValidationEventHandler
  {
    private List&lt;String&gt; messages = new ArrayList&lt;String&gt;();

    public List&lt;String&gt; getMessages() {
      return messages;
    }

    public boolean handleEvent(ValidationEvent event) {
      if (event == null)
        throw new IllegalArgumentException("event is null");

      // calculate the severity prefix and return value
      String severity = null;
      boolean continueParsing = false;
      switch (event.getSeverity()) {
        case ValidationEvent.WARNING:
          severity = "Warning";
          continueParsing = true; // continue after warnings
          break;
        case ValidationEvent.ERROR:
          severity = "Error";
          continueParsing = true; // terminate after errors
          break;
        case ValidationEvent.FATAL_ERROR:
          severity = "Fatal error";
          continueParsing = false; // terminate after fatal errors
          break;
        default:
          assert false : "Unknown severity.";
      }

      String location = getLocationDescription(event);
      String message = severity + " parsing " + location
        + " due to " + event.getMessage();
      messages.add(message);

      return continueParsing;
    }

    private String getLocationDescription(ValidationEvent event) {
      ValidationEventLocator locator = event.getLocator();
      if (locator == null) {
        return "XML with location unavailable";
      }

      StringBuffer msg = new StringBuffer();
      URL url = locator.getURL();
      Object obj = locator.getObject();
      Node node = locator.getNode();
      int line = locator.getLineNumber();

      if (url != null || line != -1) {
        msg.append("line " + line);
        if (url != null) msg.append(" of " + url);
      } else if (obj != null) {
        msg.append(" obj: " + obj.toString());
      } else if (node != null) {
        msg.append(" node: " + node.toString());
      }

      return msg.toString();
    }
  }
}
</pre>
<p>One important refinement I made to the code was to add better error handling. Parser warnings and errors are collected along with location information (such as line numbers) and the caller notified via an exception. This was necessary because the JAXB default error handling simply wrote messages to the console and reported nothing back to the caller. Due to my basic needs, I simply collected these errors and warnings into string messages. If your error-handling requirements are more sophisticated then you can collect the errors and warnings into proper objects that are returned back to the caller, who can then traverse the information and decide how to report it.</p>
<p>The unit test for this helper class is shown below. It includes a utility class with JAXB annotations to map it to XML that the tests use to exercise the functionality of the helper class. The last test exercises (in a trivial way) the additional error-handling functionality.</p>
<pre class="prettyprint">
// Copyright 2008 by Basil Vandegriend.  All rights reserved.

package com.basilv.examples.jaxb;

import static org.junit.Assert.*;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.junit.Test;

public class XmlBindingToolsTest
{
  @XmlRootElement(name = "xmltest")
  static class XmlTest
  {
    private String id;

    @XmlAttribute
    public String getId() {
      return id;
    }

    public void setId(String id) {
      this.id = id;
    }

  }

  @Test
  public void parseXml() throws Exception {

    String xml = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n"
      + "&lt;xmltest id=\"test\"/&gt;";

    StringReader reader = new StringReader(xml);
    XmlTest xmlTest = XmlBindingTools.parseXML(reader,
      XmlTest.class);
    assertNotNull(xmlTest);
    assertEquals("test", xmlTest.getId());
  }

  @Test
  public void generateXml() throws Exception {
    XmlTest xmlTest = new XmlTest();
    xmlTest.setId("test");
    StringWriter writer = new StringWriter();
    XmlBindingTools.generateXML(xmlTest, writer);
    assertEquals(
      "&lt;?xml version=\"1.0\" encoding=\"UTF-8\" "
        + "standalone=\"yes\"?&gt;\n&lt;xmltest id=\"test\"/&gt;\n",
      writer.getBuffer().toString());
  }

  @Test
  public void parseInvalidXml() throws Exception {

    String xml = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n"
      + "&lt;xmltest id=\"test\"&gt;&lt;fake/&gt;&lt;/xmltest&gt;";

    StringReader reader = new StringReader(xml);
    try {
      XmlBindingTools.parseXML(reader, XmlTest.class);
      fail("Expected Exception");
    } catch (JAXBException e) {
      // Expected case.
    }
  }

}
</pre>
<p>I did encounter some surprises when using JAXB. JAXB imposes a number of coding limitations on the mapped POJOs which are actually quite similar to Hibernate, but not documented as well. So as a general guideline, use Hibernate's restrictions and you will probably do okay. One limitation I encountered involved handling a parent-child relationship between two mapped entities. The parent class will need to have a collection of child entities. The getter method to return the collection must return the actual collection used by the class and not a copy or wrapper: JAXB appears to add children to the parent by calling the add() method on the collection returned by the getter. (See <a href="http://www.basilv.com/psd/blog/2008/exposing-mutable-objects-as-public-properties">this article</a> for why you might want to return a copy of the underlying collection.)</p>
<p>JAXB shares more than just limitations with Hibernate. Many of the mapping capabilities offered by Hibernate have analogues in JAXB. JAXB can map both fields and methods, either of which may be private. JAXB also supports mapping to custom types using the <code>@XmlJavaTypeAdapter</code> annotation. </p>
<p>Despite the limitations and surprises I ran into, I was generally pleased with JAXB. It met my original goal of providing simple parsing of XML into Java POJOs using annotations to specify the mapping. My biggest disappointment with JAXB was the poor documentation. In fact, for all but trivial parsing tasks, I would recommend writing a XML Schema definition and generating the POJOs instead of doing what I did - the documentation just does not support the approach I took.</p>
<p>The source code listed in this article is provided in the <em>Java Examples</em> project which can be downloaded from the <a href="http://www.basilv.com/psd/software">Software</a> page.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/simple-xml-parsing-using-jaxb/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Working with Java 5 Annotations</title>
		<link>http://www.basilv.com/psd/blog/2008/working-with-java-5-annotations</link>
		<comments>http://www.basilv.com/psd/blog/2008/working-with-java-5-annotations#comments</comments>
		<pubDate>Sun, 04 May 2008 21:09:17 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/blog/2008/working-with-java-5-annotations</guid>
		<description><![CDATA[Annotations are a new language feature introduced in Java 5 that allows Java code elements such as classes or methods to be annotated with structured metadata. This metadata can then be used at compile-time or at run-time by other code. Annotations are commonly used to provide configuration information for infrastructure frameworks to provide cross-cutting functionality. [...]]]></description>
			<content:encoded><![CDATA[<p>Annotations are a new language feature introduced in Java 5 that allows Java code elements such as classes or methods to be annotated with structured metadata. This metadata can then be used at compile-time or at run-time by other code. Annotations are commonly used to provide configuration information for infrastructure frameworks to provide cross-cutting functionality.</p>
<p>Using existing annotations is fairly easy - an annotation is prefixed with '@' and optionally suffixed with one or more arguments of the form (&lt;single-arg-value&gt;) or (&lt;arg1=value1&gt;, &lt;arg2=value2&gt;, ...). The annotation is added immediately before the Java code element being annotated. Below is an example using two of the standard annotations defined in Java 5 (<code>@Override</code> and <code>@SuppressWarnings</code>):</p>
<pre class="prettyprint">
package com.basilv.examples.annotations;

import java.util.ArrayList;

@SuppressWarnings("unchecked")
public class AnnotationUsage
{
  public void doStuff() {
    ArrayList list = new ArrayList();
    list.add("");
  }

  @Override
  public String toString() {
    return "AnnotationUsage";
  }
}
</pre>
<p>Defining a new annotation is a little more complicated. While an annotation is conceptually fairly similar to a Java interface - it has a name and a set of properties - the syntax for defining an annotation is, unfortunately, somewhat different from the syntax used to define an interface. This is best explained with an example:</p>
<pre class="prettyprint">
package com.basilv.examples.annotations;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target( {ElementType.TYPE, ElementType.METHOD })
public @interface MyAnnotation {
  int myProperty();
  String myPropertyWithDefault() default "";
}
</pre>
<p>The <code>@interface</code> syntax is bizarre - I mentally convert it to <code>annotation</code> - i.e. <code>public annotation MyAnnotation</code>. (I am not sure why Sun did not go with this more intuitive syntax, but I assume they did not want to create another reserved keyword for compatibility reasons - a weak reason considering that they added the assert keyword in v1.4 and the enum keyword in v5.) The declaration of individual properties is similar to the declaration of methods in interfaces except for the optional default clause that can be supplied. If no default is supplied then a value for the property must be supplied when using the annotation. </p>
<p>Annotations with no properties are allowed and are called marker annotations. Annotations with a single property by convention name the property <code>value()</code>, which allows the annotation property value to be declared without the name of the property: i.e. <code>@Annotation("value")</code>.</p>
<p>The other interesting quirk is that Java annotations (<code>@Retention</code> and <code>@Target</code>) are used when declaring an annotation. The <code>@Retention</code> annotation defines how the metadata for uses of this annotation is retained via the <code>RetentionPolicy</code> enum. The default is <code>RetentionPolicy.CLASS</code>, which stores the metadata in the compiled class file but does not necessarily load it at runtime. I think the default should have been <code>RetentionPolicy.RUNTIME</code>, which ensures that the Java VM will load the metadata and make it available at runtime. When coding my first annotation I forgot to specify the runtime retention policy. This leads to the puzzling error of not being able to retrieve at runtime the metadata on the classes using the annotation, with no indication of what was wrong. The <code>@Target</code> annotation specifies the Java code elements that this annotation can be applied to.</p>
<p>Annotation metadata is only useful if we can retrieve and act on it. The Reflections API in Java 5 was augmented with methods to retrieve annotation metadata for java code elements such as classes and methods. These annotation related methods are defined by a common interface <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/AnnotatedElement.html"><code>java.lang.reflect.AnnotatedElement</code></a>. Examples include <code>boolean isAnnotationPresent(Class)</code> and <code>T getAnnotation(Class<T>)</code>.</p>
<p>The following example shows a somewhat-realistic example of an annotation being used. I define an annotation to map URLs to methods on a class, and then implement a servlet to delegate requests to the appropriate method using this metadata. First the definition of the annotation:</p>
<pre class="prettyprint">
package com.basilv.examples.annotations;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)// or source or compile
@Target( { ElementType.TYPE, ElementType.METHOD })
public @interface WebAction {
  String url();
}
</pre>
<p>Now the class which uses this annotation to map URLs to particular methods:</p>
<pre class="prettyprint">
package com.basilv.examples.annotations;

import javax.servlet.http.*;

public class ActionExecutor
{
  private HttpServletRequest request;
  private HttpServletResponse response;

  public ActionExecutor(HttpServletRequest request,
    HttpServletResponse response) {
    this.request = request;
    this.response = response;
  }

  private void setMessage(String message) {
    request.setAttribute("message", message);
  }

  @WebAction(url = "/test")
  public void doTest() {
    // Set a message for demo purposes. Normally execute some logic.
    setMessage("test");
  }

  @WebAction(url = "/submit")
  public void submitWork() {
    // Set a message for demo purposes. Normally execute some logic.
    setMessage("submit");
  }
}
</pre>
<p>Now the servlet to handle requests by executing the appropriate method on <code>ActionExecutor</code>:</p>
<pre class="prettyprint">
package com.basilv.examples.annotations;

import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.*;
import javax.servlet.http.*;

public class DispatchingServlet extends HttpServlet
{
  @Override
  protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException {
    response.setContentType("text/html;charset=UTF-8");

    String url = request.getPathInfo();
    ActionExecutor executor = new ActionExecutor(request,
      response);

    boolean actionFound = false;
    for (Method method : ActionExecutor.class.getMethods()) {
      if (method.isAnnotationPresent(WebAction.class)) {
        WebAction action = method.getAnnotation(
          WebAction.class);
        if (url.equals(action.url())) {
          actionFound = true;
          try {
            method.invoke(executor, (Object[]) null);
          } catch (Exception e) {
            throw new RuntimeException(
              "Error invoking method " + method.getName()
                + ".", e);
          }
        }
      }
    }
    if (!actionFound) {
      request.setAttribute("message", "No action found");
    }
    RequestDispatcher rd = request
      .getRequestDispatcher("/view.jsp");
    rd.forward(request, response);
  }

  @Override
  protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException {
    doGet(request, response);
  }
}
</pre>
<p>There are a number of scenarios for which it would be useful to iterate over all classes with a particular annotation. The above example of the dispatching servlet would be more useful if it could dispatch to methods on any number of classes based on a class-level annotation. The Reflections API, however, does not provide a mechanism for obtaining all classes with a particular annotation. This is difficult functionality to provide for a <a href="http://bill.burkecentral.com/2008/01/14/scanning-java-annotations-at-runtime/">number of reasons explained by Bill Burke</a>, but since it is so valuable various open source projects such as Spring and JBoss have implemented solutions to this.</p>
<p>The source code listed in this article is provided in the <em>Java Examples</em> project which can be downloaded from the <a href="http://www.basilv.com/psd/software">Software</a> page.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/working-with-java-5-annotations/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating Custom Tags Using JSP</title>
		<link>http://www.basilv.com/psd/blog/2008/creating-custom-tags-using-jsp</link>
		<comments>http://www.basilv.com/psd/blog/2008/creating-custom-tags-using-jsp#comments</comments>
		<pubDate>Thu, 24 Apr 2008 22:12:01 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[reuse]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/blog/2008/creating-custom-tags-using-jsp</guid>
		<description><![CDATA[Java Server Pages (JSP) is a Java technology for rendering dynamic web pages. Unlike servlets written directly in Java, JSP files contain special markup to identify java or JSP code. The normal (non-markup) text is interpreted as HTML. Early in JSP's evolution, custom tags were introduced as a way of providing reusable functionality, particularly reusable [...]]]></description>
			<content:encoded><![CDATA[<p>Java Server Pages (JSP) is a Java technology for rendering dynamic web pages. Unlike servlets written directly in Java, JSP files contain special markup to identify java or JSP code. The normal (non-markup) text is interpreted as HTML. Early in JSP's evolution, custom tags were introduced as a way of providing reusable functionality, particularly reusable UI widgets, across JSP files. The original mechanism for creating these custom tags was very clunky: each tag had to be written in Java code (similar to servlets) and required extra configuration in XML to package into a tag library.</p>
<p>As of JSP version 2.0, available since Java EE 1.4, there is now support for creating custom tags using only the JSP syntax. No Java or XML is required. Each individual custom tag corresponds to a <em>tag file</em>, which is nothing more than a JSP file with a <code>.tag</code> extension located in a special directory within the WAR file: <code>/WEB-INF/tags</code>.</p>
<p>Attributes can be supplied to the tag file using a JSP directive <code>&lt;%@attribute name="&lt;some-name&gt;" required="{true|false}"%&gt;</code>. Attributes are referenced within the tag file like any other JSP variable using EL (the expression language). </p>
<p>This JSP tag library within your WAR can be referenced by other JSPs using the taglib directive: <code>&lt;%@taglib tagdir="/WEB-INF/tags" prefix="tags"%&gt;</code>.</p>
<p>The following example shows this in action. First the custom tag file <code>WEB-INF/tags/title.tag</code>:</p>
<pre class="prettyprint">
&lt;%@attribute name="title" required="true"%&gt;
&lt;%@tag description="Standard Title" pageEncoding="UTF-8"%&gt;

&lt;h1&gt;${title}&lt;/h1&gt;
</pre>
<p>Now a normal JSP file that uses this custom tag:</p>
<pre class="prettyprint">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@taglib tagdir="/WEB-INF/tags" prefix="tags"%&gt;
&lt;html&gt;
&lt;body&gt;
&lt;tags:title title="Hello World"/&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Prior to JSP 2.0 I have made reusable JSP fragments using the import directive, but this new mechanism is just as simple and much more convenient. Smart JSP editors can in fact provide lookup/completion functionality when you are invoking your custom tags.</p>
<p>The capabilities of these custom tags go far beyond what I have shown here. For more information see <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags.html">Sun's Custom Tags Tutorial</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/creating-custom-tags-using-jsp/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Automatically Populating Audit Columns in Hibernate</title>
		<link>http://www.basilv.com/psd/blog/2008/automatically-populating-audit-columns-in-hibernate</link>
		<comments>http://www.basilv.com/psd/blog/2008/automatically-populating-audit-columns-in-hibernate#comments</comments>
		<pubDate>Sun, 13 Apr 2008 22:32:30 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/blog/2008/automatically-populating-audit-columns-in-hibernate</guid>
		<description><![CDATA[Audit columns are a common design pattern used to record data creation and modification information for database tables. A typical implementation of this pattern is to add four columns to every non-static database table: CREATE_USER, CREATE_TIMESTAMP, UPDATE_USER, and UPDATE_TIMESTAMP. The create columns are populated only when a record is initially populated, while the update columns [...]]]></description>
			<content:encoded><![CDATA[<p>Audit columns are a common design pattern used to record data creation and modification information for database tables. A typical implementation of this pattern is to add four columns to every non-static database table: CREATE_USER, CREATE_TIMESTAMP, UPDATE_USER, and UPDATE_TIMESTAMP. The create columns are populated only when a record is initially populated, while the update columns are populated each time the record is updated. </p>
<p>While database triggers can be used to populate the timestamp columns, the user columns are trickier to populate. In a typical web application or three-tier architecture, individual clients do not communicate directly with the database but go through an intermediate layer – the web or application server. The data source used by the application server to connect to the database manages a pool of connections using a common application id to authenticate to the database. This avoids the overhead of a new database connection for each client request and allows a large number of user requests to be serviced by a smaller number of connections. Since it is the application, and not the user, who authenticates with the database, the database does not know the identity of the user behind the database operations, so triggers to populate user columns will not work as desired. The solution is to instead populate these columns within the application code. </p>
<p>Explicitly populating the audit columns in the code for every insert or update, however, is far from ideal - especially when using an object-relational mapping framework such as Hibernate. One of the major advantages of using Hibernate is its ability to encapsulate and hide (in a leaky fashion) the work involved in persisting to a relational database. This allows the business logic, expressed in terms of persisted domain objects, to be kept as readable and simple as possible. Cluttering this logic with calls to set the audit columns complicates the code and is error-prone – missing a single update or creation means there is a hole in the auditing. From the viewpoint of both maintainability and security, the ideal solution would be to configure Hibernate to automatically populate these audit columns whenever a record is created or updated.</p>
<p>The idea of adding orthogonal, or cross-cutting, functionality automatically to a code base is the realm of aspect-oriented programming. Hibernate supports this programming model through the use of interceptors, which allow client code to be executed as part of Hibernate's core processing. We can create an <code>AuditInterceptor</code> to set the audit columns of non-static domain objects, as identified by an <code>Auditable</code> interface. One significant issue is how to obtain the user id to set in the <code>AuditInterceptor</code>. Since the <code>AuditInterceptor</code> is registered with Hibernate and never called directly, there is no way to directly pass in the user id. The typical solution is to use a thread local singleton (i.e. an instance of <code> ThreadLocal</code>) to store the user id for the current thread. For a typical web application, at the start of processing an user's session, the user's id must therefore be registered with the <code>AuditInterceptor</code>. The code for <code>Auditable</code> and <code>AuditInterceptor</code> is shown below:</p>
<pre class="prettyprint">
public interface Auditable
{

  public String getCreateUserId();

  public void setCreateUserId(String createUserId);

  public String getUpdateUserId();

  public void setUpdateUserId(String updateUserId);

}

public class AuditInterceptor extends EmptyInterceptor
{

  private static ThreadLocal<String> userPerThread = new ThreadLocal<String>();

  /**
   * Store the user for the current thread.
   * @param user Cannot be null or empty.
   */
  public static void setUserForCurrentThread(String user) {
    userPerThread.set(user);
  }

  /**
   * Get the user for the current thread.
   * (Used primarily for testing).
   * @return the current user.
   */
  public static String getUserForCurrentThread() {
    return userPerThread.get();
  }

  @Override public boolean onFlushDirty(Object entity,
    Serializable id, Object[] currentState,
    Object[] previousState, String[] propertyNames,
    Type[] types) {

    boolean changed = false;

    if (entity instanceof Auditable) {
      changed = updateAuditable(currentState, propertyNames);
    }
    return changed;
  }

  @Override public boolean onSave(Object entity,
    Serializable id, Object[] currentState,
    String[] propertyNames, Type[] types) {

    boolean changed = false;

    if (entity instanceof Auditable) {
      changed = updateAuditable(currentState, propertyNames);
    }
    return changed;

  }

  private boolean updateAuditable(Object[] currentState,
    String[] propertyNames) {
    boolean changed = false;
    for (int i = 0; i < propertyNames.length; i++) {
      if ("createUserId".equals(propertyNames[i])) {
        if (currentState[i] == null) {
          currentState[i] = userPerThread.get();
          changed = true;
        }
      }
      if ("updateUserId".equals(propertyNames[i])) {
        currentState[i] = userPerThread.get();
        changed = true;
      }
    }
    return changed;
  }

}
</pre>
<p>The <code>AuditInterceptor</code> must be registered with Hibernate. This can be done when the Hibernate session is created, as shown below. Depending on how sessions are created within your code base, you could also provide the current user id to the constructor of <code>AuditInterceptor</code>.</p>
<pre class="prettyprint">
Session session = sessionFactory.openSession(new AuditInterceptor());
</pre>
<p>The source code listed in this article is provided in the <em>Java Examples</em> project which can be downloaded from the <a href="http://www.basilv.com/psd/software">Software</a> page.</p>
<p>This article is one of a series on <a href="http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks">Hibernate Tips &#038; Tricks</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/automatically-populating-audit-columns-in-hibernate/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Improving Performance via Eager Fetching in Hibernate</title>
		<link>http://www.basilv.com/psd/blog/2008/improving-performance-via-eager-fetching-in-hibernate</link>
		<comments>http://www.basilv.com/psd/blog/2008/improving-performance-via-eager-fetching-in-hibernate#comments</comments>
		<pubDate>Sun, 16 Mar 2008 01:35:46 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/blog/2008/improving-performance-via-eager-fetching-in-hibernate</guid>
		<description><![CDATA[My previous article started discussing Hibernate relationships, focusing on lazy versus non-lazy relationships. This article continues the theme by discussing how to improve performance when dealing with relationships in Hibernate through a feature called eager fetching. Hibernate's abstraction of database access behind getter and setter methods on domain objects hides potentially inefficient database access. Mindlessly [...]]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://www.basilv.com/psd/blog/2008/avoid-non-lazy-relationships-in-hibernate">previous article</a> started discussing Hibernate relationships, focusing on lazy versus non-lazy relationships. This article continues the theme by discussing how to improve performance when dealing with relationships in Hibernate through a feature called eager fetching.</p>
<p>Hibernate's abstraction of database access behind getter and setter methods on domain objects hides potentially inefficient database access. Mindlessly using Hibernate without considering the implications for the database operations being performed can lead to significant performance hits. One of the most significant performance problems is the N+1 query problem, where iterating over a collection of entities and accessing a related entity for each will result in one query to return the collection, and then a separate query for each entity to retrieve its related entity. For N entities in the collection, this is a total of N+1 queries. This is quite inefficient, especially for larger values of N, considering that a single database query can be written to return all of the related entities for all the entities of the collection. I touched on this issue previously in the context of non-lazy relationships, but it still occurs with lazy relationships. To provide a concrete example, I will refer to the following object model (the same as in my previous article):<br />
<a href='http://www.basilv.com/psd/wp-content/uploads/2008/03/hibernaterelationshipsclassdiagram.png' title='Class Diagram'><img src='http://www.basilv.com/psd/wp-content/uploads/2008/03/hibernaterelationshipsclassdiagram.png' alt='Class Diagram' /></a></p>
<p>The corresponding classes are summarized as follows:</p>
<pre class="prettyprint">
class Customer {
  public Collection<Order> getOrders();
  public void addOrder(Order order);
}
class Order {
  public Customer getCustomer();
  public PaymentMethod getPaymentMethod();
  public void setPaymentMethod(PaymentMethod m);
}
class PaymentMethod {
  public Order getOrder();
}
</pre>
<p>Let us say I want to give a bonus to a customer who has only paid by cash. The naive implementation for a given customer would be the following:</p>
<pre class="prettyprint">
public boolean qualifiesForBonus(Customer customer) {
  for (Order order : customer.getOrders() ) {
    PaymentMethod paymentMethod = order.getPaymentMethod();
    if (!paymentMethod.isCash()) {
      return false;
    }
  }
  return true;
}
</pre>
<p>This implementation results in N+1 queries, which may not be so bad if the customer has only a few orders. But what if we want to calculate this for all customers? Now it is M(N+1) + 1 queries (where M is the number of customers), and the cost becomes much higher. This question can be answered with a single SQL query:</p>
<pre class="prettyprint">select * from Customer c join Order o on o.customer_FK = c.id
where not exists (
select * from PaymentMethod m where m.order_FK = o.id and m.type <> 'CASH'
)</pre>
<p>It would be nice to be able to calculate this logic across relationships using our domain objects while efficiently retrieving them via a single query. Hibernate's eager fetching feature lets you accomplish this. Eager fetching allows you to load related entities at the same time using a single query. You simply tell Hibernate in your query by criteria or HQL to fetch the associated entity. Behind the scenes, Hibernate generates an SQL statement that joins to the associated entity table. The result set includes the columns from both the base entity and the associated entity, which Hibernate converts into the appropriate domain objects.</p>
<p>For an example, we will use Hibernate HQL to retrieve all customers in order to calculate if they qualify for a bonus. We want to eagerly fetch the orders and payment methods used in the calculation ahead of time to avoid multiple SQL queries being issued. The following code does this:</p>
<pre class="prettyprint">List<Customer> list = session.createQuery(
  "select c from Customer c left join fetch c.orders o " +
  "left join fetch o.paymentMethod p").list();</pre>
<p>The list of customers returned already has the Order and PaymentMethod objects loaded in a single SQL query, so now when you iterate over the list and call the <code>qualifiesForBonus()</code> method, the processing will be done entirely in memory with no additional SQL queries.</p>
<p>As wonderful as eager fetching is, it comes with several surprises. Understanding the different types of SQL joins is important. The above HQL specifying "left join" is shorthand for "left outer join", which means that Customers without Orders will still be returned. If you just specify "join", which is shorthand for "inner join", then such Customers will not be returned. Let us say that the database holds three customers with two orders and one customer with no orders. The resulting SQL using "left join" will return seven rows (3 * 2 + 1), whereas using "join" it will return only six rows. For the "left join" query, how many elements will the resulting list created by Hibernate contain? You might expect the answer to be four, for the four customers in the database, but the answer is seven. Hibernate does only return four instances of Customer, as per its guarantee of having a single Java instance of a given domain object per session, but three of these instances are referenced twice in the list. Given the strong object-oriented nature of HQL and Hibernate, I found it surprising that such an object-based query language would return duplicate references to match what the SQL query returns. The apparent explanation from the Hibernate website for this behavior is that there are situations where this the desired behavior (although I cannot think of any myself). Fortunately, there is a simple solution. Adding the keyword distinct to the query (i.e. "select distinct c from ...") will not change the SQL query or the number of results it returns, but it will cause Hibernate to eliminate the duplicate references and return four elements in the list as expected.</p>
<p>To use eager fetching when doing query by criteria, use the <code>setFetchMode()</code> method. For example:</p>
<pre class="prettyprint">List<Customer> list = session.createCriteria(Customer.class)
  .setFetchMode("orders", FetchMode.JOIN).list();</pre>
<p>Hibernate will determine whether to do an inner or outer join: if the relationship is optional, an outer join will be used, potentially returning duplicate references as described above.</p>
<p>The entire point of eager fetching is to achieve better performance. If you try to eagerly fetch too many relationships, however, especially optional relationships resulting in outer joins, you may find your performance becomes worse, not better. Each additional outer join adds another dimension to the Cartesian product representing the result of the query, and too large a result set will cause performance to be worse than without the eager fetching. Hibernate 2 actually limited eager fetching to a single to-many relationship to help prevent this from occurring. Hibernate 3 drops this restriction, leaving you responsible for the consequences.</p>
<p>There are other surprises lurking in Hibernate's implementation of eager fetching. I recommend referring to <a href="http://www.hibernate.org/">Hibernate's online documentation</a> for more information, particularly the FAQs.</p>
<p>This article is one of a series on <a href="http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks">Hibernate Tips &#038; Tricks</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/improving-performance-via-eager-fetching-in-hibernate/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Avoid Non-Lazy Relationships in Hibernate</title>
		<link>http://www.basilv.com/psd/blog/2008/avoid-non-lazy-relationships-in-hibernate</link>
		<comments>http://www.basilv.com/psd/blog/2008/avoid-non-lazy-relationships-in-hibernate#comments</comments>
		<pubDate>Thu, 06 Mar 2008 05:39:07 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/blog/2008/avoid-non-lazy-relationships-in-hibernate</guid>
		<description><![CDATA[Support for entity relationships is a great time-saving feature in Hibernate, but it can also be a trap for the unsuspecting developer. Handling relationships between entities can be a complex business, and I for one am glad for all the support that Hibernate provides. Hibernate's assistance, however, can do more harm than good when it [...]]]></description>
			<content:encoded><![CDATA[<p>Support for entity relationships is a great time-saving feature in <a href="http://www.hibernate.org/">Hibernate</a>, but it can also be a trap for the unsuspecting developer. Handling relationships between entities can be a complex business, and I for one am glad for all the support that Hibernate provides. Hibernate's assistance, however, can do more harm than good when it comes to performance considerations. Because Hibernate does such a good job of hiding what SQL is generated for entity relationships and when it is executed, it is all too easy to produce poorly performing code and not realize it. Hibernate does provide a number of features to optimize performance, especially for relationships, such as the first and second level cache, lazy loading, and eager fetching. This multitude of features, however, can compound the problem when developers are unaware of them or of how they work. </p>
<p>This article focuses on lazy versus non-lazy relationships. In Hibernate 3 relationships are by default lazy: when an entity is loaded, the related entity or collection will not be loaded until it is accessed. In Hibernate 2, the default was non-lazy relationships. This default was changed in Hibernate 3 because of all the problems people encountered with non-lazy relationships. Despite the change in default in Hibernate 3, I have still seen developers explicitly use non-lazy relationships in the mistaken belief that they will provide a performance boost. I believe their assumption is that because Hibernate loads the non-lazy related entities at the same time as it loads the base entity, Hibernate must do this in a single SQL statement which is therefore more efficient. This is not true. </p>
<p>Hibernate's actual behavior is easy to see once you <a href="http://www.basilv.com/psd/blog/2008/hibernate-and-logging">turn on SQL logging</a>. Hibernate will issue one query to load the entities, and then issue one or more additional SQL queries in order to load the related entities. This does not seem so bad for a single relationship, but consider a typical application with a network of related entities. If all the relationships are non-lazy, then loading one entity will load all the related entities in the network. If collection relationships are involved the problem can become even worse. In certain scenarios, such as when loading a collection of child records that each have a non-lazy relationship to another entity, Hibernate will perform 1+N queries: one query to load the collection of children, and one query per child entity (N queries total) to load the related record for each child. </p>
<p>To provide a concrete example, consider the following object model.<br />
<a href='http://www.basilv.com/psd/wp-content/uploads/2008/03/hibernaterelationshipsclassdiagram.png' title='Class Diagram'><img src='http://www.basilv.com/psd/wp-content/uploads/2008/03/hibernaterelationshipsclassdiagram.png' alt='Class Diagram' /></a></p>
<p>The corresponding classes are summarized as follows:</p>
<pre class="prettyprint">
class Customer {
  public Collection<Order> getOrders();
}
class Order {
  public Customer getCustomer();
  public PaymentMethod getPaymentMethod();
}
class PaymentMethod {
  public Order getOrder();
}
</pre>
<p>Let us assume that the relationship between Order and PaymentMethod is non-lazy. What happens when we have a single Customer and access its orders? Calling the getOrders() method on Customer when Customer is persistent and the orders collection has not yet been initialized causes Hibernate to issue a query to load the orders:
<pre class="prettyprint">select * from Order where Customer_FK = ?</pre>
<p>Each row returned by this query is converted by Hibernate into an Order instance which is then associated with the existing Customer object. Because the relationship to PaymentMethod is non-lazy, however, Hibernate must also load the corresponding PaymentMethod object via an additional query. I.e.
<pre class="prettyprint">select * from PaymentMethod where Order_FK = ?</pre>
<p>This PaymentMethod query is executed for each Order, so if there are N orders on the customer, Hibernate will execute N+1 queries. This is despite the relationship between Order and PaymentMethod being one-to-one. If it was an one-to-many relationship instead with M PaymentMethod instances for each Order, the performance would be even worse: 1+N*M queries total. On a recent project where multiple relationships were configured as non-lazy (compared to just one relationship in this example), I have seen a single operation result in hundreds of queries being executed to load in almost the entire related object graph. </p>
<p>The solution to this problem is easy: use only lazy relationships. I have a hard time thinking of any scenario where a non-lazy relationship would be a good idea. They certainly do not help performance, since the same set of SQL queries is issued for lazy and non-lazy relationships - it is just that lazy relationships result in queries being deferred until they are needed. If you do want to improve the performance of loading related entities then <a href="http://www.basilv.com/psd/blog/2008/improving-performance-via-eager-fetching-in-hibernate">eager fetching is the feature to use</a>.</p>
<p>This article is one of a series on <a href="http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks">Hibernate Tips &#038; Tricks</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/avoid-non-lazy-relationships-in-hibernate/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hibernate and Logging</title>
		<link>http://www.basilv.com/psd/blog/2008/hibernate-and-logging</link>
		<comments>http://www.basilv.com/psd/blog/2008/hibernate-and-logging#comments</comments>
		<pubDate>Sat, 23 Feb 2008 22:08:40 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/blog/2008/hibernate-and-logging</guid>
		<description><![CDATA[Hibernate tries to hide the details of dealing with relational databases, but it is at best a leaky abstraction. At its most basic level, Hibernate is a framework that issues SQL commands to the database. Sometimes it does not do what you would expect or want (more on that in future articles). Therefore it is [...]]]></description>
			<content:encoded><![CDATA[<p>Hibernate tries to hide the details of dealing with relational databases, but it is at best a <a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html">leaky abstraction</a>. At its most basic level, Hibernate is a framework that issues SQL commands to the database. Sometimes it does not do what you would expect or want (more on that in future articles). Therefore it is very useful at times to monitor or review the SQL being produced by Hibernate. The book <a href="http://www.amazon.ca/gp/product/1932394885?ie=UTF8&#038;tag=basilvandegri-20&#038;linkCode=as2&#038;camp=15121&#038;creative=330641&#038;creativeASIN=1932394885">Java Persistence with Hibernate</a><img src="http://www.assoc-amazon.ca/e/ir?t=basilvandegri-20&#038;l=as2&#038;o=15&#038;a=1932394885" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> covers this topic primarily by discussing the <code>show.sql</code> hibernate configuration property which writes generated SQL to the console. I have found this far too limiting: I instead want the SQL logged in my application's log (i.e. as produced by log4j) to receive all the advantages that a central logging system can provide. This can be accomplished by turning on <code>DEBUG</code> logging for the logging context <code>org.hibernate.SQL</code>. If you are using log4j, add the following line to your log4j.properties file: </p>
<pre class="prettyprint">
log4j.logger.org.hibernate.SQL=DEBUG
</pre>
<p>One limitation of this SQL logging is that it reports the SQL statement but not the values of the parameters. Since Hibernate almost always uses prepared statements with parameters, this is often an annoying limitation. Fortunately, Hibernate does allow the logging of parameter values: turn on <code>DEBUG</code> logging for the logging context <code>org.hibernate.type</code>. Unfortunately, this results in very verbose logs since each parameter value for each query is a separate log entry. A sample log entry for a single insert statement is shown below.</p>
<pre class="prettyprint">
07 Feb 2008 13:30:52,596 DEBUG insert into example.customer (CATEGORY,
CREATE_USER_ID, CREATE_TIMESTAMP, UPDATE_USER_ID, UPDATE_TIMESTAMP, OID)
values (?, ?, ?, ?, ?, ?) - org.hibernate.SQL [main] [44513 ms]

07 Feb 2008 13:30:52,596 DEBUG binding 'S' to parameter: 1 -
hibernate.type.StringType [main] [44513 ms]

07 Feb 2008 13:30:52,596 DEBUG binding 'junit test' to parameter: 2 -
hibernate.type.StringType [main] [44513 ms]

07 Feb 2008 13:30:52,596 DEBUG binding '2008-02-07 13:30:52' to parameter: 3 -
hibernate.type.DbTimestampType [main] [44513 ms]

07 Feb 2008 13:30:52,596 DEBUG binding '2008-02-07 13:30:52' to parameter: 4 -
hibernate.type.TimestampType [main] [44513 ms]

07 Feb 2008 13:30:52,596 DEBUG binding 'junit test' to parameter: 5 -
hibernate.type.StringType [main] [44513 ms]

07 Feb 2008 13:30:52,596 DEBUG binding '2691102' to parameter: 6 -
hibernate.type.LongType [main] [44513 ms]
</pre>
<p>I much prefer the way that Spring JDBC logs SQL statements – both the SQL and the list of parameter values are logged as a single statement. If you know how to do this in Hibernate, I would appreciate hearing from you.</p>
<p>Hibernate uses Apache's <a href="http://commons.apache.org/logging/">commons-logging</a> to abstract the actual logging mechanism: typically either <a href="http://logging.apache.org/log4j/index.html">log4j</a> or Java logging (introduced in Java 1.4). I always use log4j myself, and normaly including the log4j jar file in the classpath is sufficient to have commons-logging use log4j. When running code in an application server, however, this is not always the case. I have had issues with both WebSphere and WebLogic application servers configuring commons-logging for some other behavior and having that setting 'leak' into my application. As a result, instead of having log messages from Hibernate appear in the application log along with the rest of the log statements produced directly with the log4j API, the Hibernate log messages appear elsewhere. In WebSphere 6.1, I had them going to the console (standard out). The simplest solution is to add a configuration file named <code>commons-logging.properties</code> to the root of your application's classpath with the following content that instructs commons-logging to use log4j for logging:</p>
<pre class="prettyprint">
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
</pre>
<p>This article is one of a series on <a href="http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks">Hibernate Tips &#038; Tricks</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/hibernate-and-logging/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Hibernate Tips and Tricks</title>
		<link>http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks</link>
		<comments>http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks#comments</comments>
		<pubDate>Sat, 23 Feb 2008 21:58:22 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks</guid>
		<description><![CDATA[Hibernate is a de facto standard for object-relational mapping. One of my recent projects involved the use of the latest version of Hibernate (3.2). Since I had not used Hibernate since its version 2 days, I picked up the authoritative reference Java Persistence with Hibernate which is co-authored by Gavin King, the founder of Hibernate. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.hibernate.org/">Hibernate</a> is a de facto standard for object-relational mapping. One of my recent projects involved the use of the latest version of Hibernate (3.2). Since I had not used Hibernate since its version 2 days,  I picked up the authoritative reference <a href="http://www.amazon.ca/gp/product/1932394885?ie=UTF8&#038;tag=basilvandegri-20&#038;linkCode=as2&#038;camp=15121&#038;creative=330641&#038;creativeASIN=1932394885">Java Persistence with Hibernate</a><img src="http://www.assoc-amazon.ca/e/ir?t=basilvandegri-20&#038;l=as2&#038;o=15&#038;a=1932394885" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> which is co-authored by Gavin King, the founder of Hibernate. I carefully perused the book prior to starting development and found it useful and comprehensive. </p>
<p>As development proceeded, however, I discovered a number of surprises that Hibernate threw my way and a number of seemingly common issues that arose that I either could not find in the book or were inadequately covered. So I wanted to share these Hibernate tips &#038; tricks with you. Rather than produce one large article consisting of a collection of unrelated tips, I decided to produce separate articles, each on a focused subject. Below I list these specific tips &#038; tricks articles:</p>
<ul>
<li><a href="http://www.basilv.com/psd/blog/2008/hibernate-and-logging">Hibernate and Logging</a>: Provides tips on how to log the SQL created by Hibernate.</li>
<li><a href="http://www.basilv.com/psd/blog/2008/avoid-non-lazy-relationships-in-hibernate">Avoid Non-Lazy Relationships</a>: Why lazy relationships should always be used.</li>
<li><a href="http://www.basilv.com/psd/blog/2008/improving-performance-via-eager-fetching-in-hibernate">Improving Performance via Eager Fetching in Hibernate</a>: How eager fetching works and how to use it.</li>
<li><a href="http://www.basilv.com/psd/blog/2008/automatically-populating-audit-columns-in-hibernate">Automatically Populating Audit Columns in Hibernate</a>: How to easily populate audit columns for your entire application.</li>
<li><a href="http://www.basilv.com/psd/blog/2010/avoiding-caching-to-improve-hibernate-performance">Avoiding Caching To Improve Hibernate Performance</a>: When overuse of Hibernate's cache can hurt performance.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2008/hibernate-tips-and-tricks/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

