Mar 10 2008

Auto-Expanding Collections as JDBC Parameters with Spring SimpleJdbcTemplate

Tag: development, hibernate, java, jdbc, springpmularien @ 7:54 am

One of the most irritating limitations of plain JDBC is that queries with a variable number of parameters are notoriously painful to deal with. The most common case of this is with the IN clause, which by definition is intended to accept a variable length argument list. JDBC, for those who don’t know, does not allow variable-length bound parameters.

Having worked with Spring’s Hibernate abstraction (HibernateTemplate) for some time, I have gotten used to Spring’s value-added feature of expanding Collections bound to HQL parameters (it’s a shame that Hibernate doesn’t natively support this, AFAIK). I was pleasantly surprised to find out that Spring offers JDBC support for this feature as well. Here’s a simple set of examples…

Continue reading “Auto-Expanding Collections as JDBC Parameters with Spring SimpleJdbcTemplate”


Dec 11 2007

Solving Problems with International (UTF-8) Data using Hibernate, Oracle, and Tomcat

Tag: hibernate, java, oracle, tomcatpmularien @ 6:19 am

Ran into a very interesting issue the other day relating to storing NLS character data in Oracle via Hibernate, running in the Tomcat servlet container. It turns out the solution is not entirely obvious (or well-documented), so I thought I’d jot the important bits down.

NVARCHAR2 is a data type assigned to a column that is used to store NLS data, most generally multi-lingual (UTF-8 or equivalent). This differs from the typical VARCHAR2 data type, which is usually intended for storing data in the local character set (see this for a weak explanation).

In theory you should not have to do anything different in your JDBC-based application to write to an NVARCHAR2 column vs a VARCHAR2 column, since String type in Java is UTF-8.

However, the evil Oracle JDBC driver rears its ugly head again (if you’ve been working with Oracle JDBC for any length of time, you know what I’m talking about ;) )!
Continue reading “Solving Problems with International (UTF-8) Data using Hibernate, Oracle, and Tomcat”


Nov 28 2007

Bleeding Edge Transactional Wicket Web Applications with Warp and Guice

Tag: guice, hibernate, java, learning, spring, warp, wicketpmularien @ 8:47 pm

One of the reasons that I think Spring has become so popular in web applications is that there simply hasn’t been another widespread web application stack that (1) is free, (2) is not Java EE, and (3) doesn’t involve JSF.

Wicket (which I’ve written about in passing before) is a great component-based web framework that integrates nicely with Spring (and therefore Hibernate and/or JPA), making it a great choice for a web stack that looks like this:

  • Wicket [web tier]
  • Spring [transactional / business tier]
  • Hibernate [data access tier]

But what other choice is there for a transactional / business layer if you (for whatever reason) don’t want to use Spring?

Fortunately, Dhanji Prasanna has been hard at work on a transactional framework for Guice called warp-persist.

Continue reading “Bleeding Edge Transactional Wicket Web Applications with Warp and Guice”


Nov 02 2007

Guice Impressions from a Spring Veteran

Tag: guice, hibernate, java, spring, wicketpmularien @ 9:28 pm

I decided to do a quick investigation of Google’s Guice dependency injection framework. The impetus for this was the recent excitement on TheServerSide regarding Guice vs. Spring, and the ensuing (and always entertaining) TSS discussion thread.

Being a long-time (4+ years) Spring user myself, I decided to download Guice, read through the docs, and have a go at it. I hope this perspective as a long-time Spring user is useful if you’re considering looking at Guice (I admit that Guice has been available for some time, and I’ve just now gotten around to trying to code with it). Craig Walls has an excellent writeup on Guice vs Spring along with a good, detailed example, done in March 2007.

Background

I’ll try to keep this entry at a relatively high level, directed at people who might be considering Guice and where it fits in an application stack vis-a-vis Spring.
Since I’ve recently developed a couple good applications with Spring, I decided a first crack at learning Guice would be to see how I would apply it the simpler of the two projects, and replace our use of Spring 2 with Guice instead. The application in question is a pretty standard Web-based application, using Wicket 1.2, Spring 2, and Hibernate 3.

Guice in a Nutshell

I have to say that the quality of the documentation for Guice is excellent. Bob Lee and the Guice team have done a great job providing a well-written and concise user guide which covers the breadth of Guice through some good examples. Additionally (happily) the Guice crew apparently actually understands how to write quality Javadoc! Take a look at the Javadoc for Binder (one of the key concepts in Guice) for an exquisite example of code documentation. Nice to see in an open-source project!

I was able to come up with some simple examples where I could wire interfaces and implementations together with annotations, without annotations, and perform simple binding of configuration parameters. These were straightforward and intuitive, and the use of method chaining along with the binder DSL made for some very readable, Ruby-esque code.

Guice is definitely a very elegant way of building an application using good DI principles. I tried very hard to suspend my prior bias towards Spring-style XML configuration, which can get very hairy if you have a project with hundreds or thousands of beans spread across multiple XML files.

I could see Guice working very well in a strictly component-based environment where code is widely shared across applications, with very loose coupling and good attention to API contracts — someplace like Google, for instance.

Guice and the “Real World”

Therein lies the problem, however. I am an application developer by trade, and those applications have generally been web-based, and involve the typical 3 tiers - web, business, and data. Guice shines at the business tier, but quite literally has almost nothing to address the inherent complexities of managing dependencies across tiers.

Guice provides very short shrift to the web tier, giving a modicum of session- and request-scoped bindings, with (shockingly!) almost no formal documentation. No examples exist on the Guice site to provide the newbie with any clue how to tie it into a real-world application. Guice relies on “viral” dependency injection - in order to get a Guice-injected resource, you need access to the actual Injector object. The common suggestion for this is to stuff this reference in a static or ThreadLocal. Unfortunately, Guice doesn’t inherently provide you with a canned way to do this - it’s left as an exercise to the reader.

The “exercise to the reader” issue is one you’ll run across often, and I think is a testament to the laser focus of the Guice framework. Guice is really intended to be (only?) a great dependency injection and management framework, but it needs a lot of integration with other bits in your stack to make it work.

In my test case (Wicket / Spring / Hibernate-based application), I had some amount of success.

Wicket 1.3 beta 4 offers built-in support for Guice injections into components, and after going through the well-documented Wicket 1.2 to 1.3 upgrade pain, it “just worked” as easily as the Wicket - Spring integration does. This is a result of Alastair’s stellar work on the Wicket project - great job!

Unfortunately, the data tier proved to be more problematic. Although there are various suggestions about design patterns on the Guice newgroups, including copious feedback from Bob and the Guice team, there’s not yet a good choice for integrating Guice with your data tier (ORM or JDBC layer). A project that looks promising is the warp-persist module from Dhanji Prasana, which integrates Guice and annotations around a transactional framework that can itself wrap Hibernate or JPA. I plan on evaluating this very soon, although at this point it is in heavy development, and as such suitable only for development environments. One of the reason that I am excited about the warp-persist project is that the (only?) author, Dhanji, is very active on the Guice newgroups, as well as providing some excellent Warp-related articles on his blog.

So, if you were to try to build a web application stack with Guice, it might look like this:

  • Web Tier: Wicket
  • Business Tier: Guice / Warp-persist
  • Data Tier: JPA

This certainly seems reasonable, and I bet around the time that Warp gets more stable, and Guice 1.1 (or 2.0?) is released, I’ll start getting good questions from folks who want to use it.

… and Spring

Contrast the discussion of the previous section with Spring, which has great appeal to architects and business types, because it takes the “kitchen sink” approach and literally can manage your whole top two tiers (web and business/service), down through transaction management and into the data tier. For architects or technical designers, Spring is still a pretty safe bet to build an application stack with, simply because it does almost everything you need already.

Trying to convert an existing application which uses broad features of Spring into an application based solely on Guice is basically nonsensical - if you’ve invested a lot in the breadth of Spring, you’re going to be very disappointed in the lack of breadth available in Guice.

Even simple things that Spring does, such as externalizing property bindings into properties files (a must for applications that are configured per environment, or per customer), are roll-your-own in Guice. Although Guice may be a more elegant way to tie dependencies together, you’ll find that it requires a lot of hard thinking on how to “do the right thing,” a task which many pragmatic developers will have a hard time with.

Which should you use?

As with many other things, the right tool for the right job. I could see Guice being ideal for non-web based applications, and generally promoting good design principles. It is extremely lightweight, and as such could be used in client-side apps launched via Java Web Start. Definitely worth paying attention to as it, and the community around it, develops.

(The curious reader may wonder why I haven’t touched the XML-vs-java configuration argument. I will explore that in a later article when I have time to review the changes and enhancements in Spring 2.5, nee Spring 2.1!)

Thanks for reading!


Oct 29 2007

Quick Tip: Using Spring and Hibernate Annotations

Tag: hibernate, java, jpa, springpmularien @ 10:01 am

Hibernate Annotations provides a complete implementation of EJB 3 / JPA-compatible annotations. It is possible to use Hibernate annotations with the native Hibernate API. You use Hibernate annotated classes in the same way that you would use XML mapping files. This is a great strategy if you’d like to prepare for a transition to JPA, but aren’t quite ready due to some of the known deficiencies in the API.

It is also possible to tie the annotated classes (and Hibernate) together with Spring’s transaction management. Unfortunately, the Spring documentation on ORM using Hibernate doesn’t cover how to do this. I’ll show you how, below.

To use annotated classes instead of XML mapping files, simply reference Hibernate like so in your Spring XML configuration file (note this requires Spring 2.0+) (line breaks denoted with »):

&lt;bean id="sessionFactory" class="<strong>org.springframework.orm.hibernate3. » annotation.AnnotationSessionFactoryBean</strong>"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;property name="annotatedClasses"&gt; &lt;list&gt; &lt;value&gt;com.foo.Employee&lt;/value&gt; ...

In describing this, I assume that you’ve already got your basic Spring and Hibernate configuration working (there are plenty of great examples available if you don’t).

And that’s basically it - all the classes listed in “annotatedClasses” need to have JPA-compatible annotations (@Entity or @MappedSuperclass). This allows you to avoid heavy XML mappings and take one step closer to JPA / Java EE 5.


Apr 25 2007

Handy Hibernate 3 Logger Reference

Tag: development, hibernatepmularien @ 8:49 am

In my [admittedly] limited 3 years of using Hibernate, I’ve found that a lot of folks are confused about what loggers to use when trying to debug Hibernate issues.

These people (myself included, on occasion) will end up opening the floodgates and doing something like this (log4j) syntax:
&lt;logger name="org.hibernate"&gt; &lt;level value="DEBUG"&gt; &lt;/level&gt; &lt;/logger&gt;

While this (obviously) works, Hibernate is nothing if not verbose in its logging, and this will easily generate megabytes of Hibernate logs.

Hibernate uses the standard logging pattern of naming loggers after the classes they’re enclosed in, as suggested by Sun itself. So if you’re familiar with the Hibernate code, it can be fairly easy to pick out the right package qualifier in your logging configuration to get logging where you want it.

Unfortunately, many/most developers aren’t familiar enough with the Hibernate source code to know these things off the top of their heads.

Thankfully, the Hibernate folks have kindly documented some logging settings, including logging of SQL (which is the simple shortcut org.hibernate.SQL.

I have a couple more useful loggers to add to the list:

  • org.hibernate.engine.query.HQLQueryPlan - which will display the source of any HQL query executed prior to execution and parameter binding
  • org.hibernate.engine.QueryParameters - will display the name / value pairs of query parameters bound to HQL queries

I’ll plan on updating this post with additional information as I run across it.