Friday, August 3, 2012

PDO lastInsertId returning 0 (zero)

PDO::lastInsertId() should return the id of the last inserted row into the database. But sometimes it might return 0. Following are the reasons that could cause this:

  • Last executed query was not an insert query
  • The query statement was not executed with PDOStatement::execute()
  • There is a semicolon at the end of the query
Basically, the first is the real cause, and others are just variations.

Thursday, July 26, 2012

Generic typesafe DAO with Guice and Hibernate

DAOs are an important part of many applications in the Java world. Most if not all entity classes will need a DAO for basic operations such as retrieval, persistence, updating and deletion. Writing a DAO for each and every entity can be a daunting task, not to mention that those operations will be duplicated among other DAOs.

Fortunately, there is an easy way to deal with this problem. It's possible to create a single DAO implementation which can be used to operate on any entity class. It is accomplished using Java Generics and Guice's TypeLiteral. For backwards compatibility with previous platforms, generic type information is erased during compilation, and therefore there's no way to determine the generic class at run-time. TypeLiteral tries to workaround this limitation allowing the generic type to be retained and queried at run-time. Basically, it works as a wrapper, and thus DAO bindings will look a bit different.

Wednesday, September 21, 2011

Jersey + Jackson: Serialize only annotated fields or methods with @JsonProperty

By default, when serializing objects, Jackson will auto-detect all public no-argument non-static getter methods and include them as properties in the final result (JSON string). I wanted Jackson to use only annotated methods and ignore rest of the methods of my object. To accomplish this we need to turn off the AUTO_DETECT_GETTERS feature in SerializationConfig object by configuring our ObjectMapper which holds an instance of SerializationConfig. I couldn't manage to inject a preconfigured SerializationConfig or ObjectMapper object. Then I found out that we need create an ObjectMapper provider class that implements ContextResolver, and annotate it with @Provider. This provider should then return an instance of ObjectMapper. This is where we will configure the object.

Tuesday, September 20, 2011

Guice + Jersey: The ResourceConfig instance does not contain any root resource classes

This happens because Jersey cannot or doesn't know how to find Resource classes. Jersey has to be told the package name in which Resource classes are located. The most obvious way is to add an init-param to the web.xml file. But since I'm using Guice servlets, I wanted to do it in Guice-way.