Hibernate never stops surprising me February 28th, 2010

I have a simple form in my web application where a user can fill in his personal details and address details. User specific fields include firstName, middleName and lastName while Address specific fields include street, city and zip. On the server side, I have POJOs for User and Address. Finally I use Hibernate to map these POJOs to the database. Since, the Address will not be used outside the context of the User, I decided to map it as a Component of the User class.

The User class and its corresponding mapping is given below:

@Entity @Table(name = "user")
public class User {

     @Column(name = "first_name")
     private String firstName;

     @Column(name = "middle_name")
     private String middleName;

     @Column(name = "last_name")
     private String lastName;

     @Embedded
     private Address homeAddress;

     ... Getters and Setters
}

The Address class is mapped to User as a component. You can see the specifics of the mapping below.

@Embeddable
public class Address {
     @Column(name = "address_street")
     private String street;

     @Column(name = "address_city")
     private String city;

     @Column(name = "address_state")
     private String state;

     ... Getters and Setters
}

As you may already know, mapping components using hibernate is a very useful feature. This feature and support for nested components and components referring to other entities are the primary source of support for rich and fine grained domain model in hibernate. But while i was using Component mapping, I recently stepped on an interesting Feature (or it could be an Issue) and I was happily surprised by it.

Want to know the surprise? Keep reading…

In this case you map an Address as a value type using @Embedded annotation in the “homeAddress” field of the User class. The Address class itself is declared to be @Emeddable. This is the standard Hibernate/JPA way to map value types. The Address class has street, city and zip and it gets stored into the same table as the User class’s table. Now, when you insert an instance of User into the database, while specifying all null values for Address’s fields maybe because the user didn’t give his address, then what would you expect in return at some point in time when you retrieve this User back from the database.

I for one expected user.getAddress() will return an Address instance. Then address.getStreet() will return null. But that is not what happened. user.getAddress() returned null by itself. That was interesting and even helped me in my case because, if the user hasn’t given any details for his home address, then it probably means that his address itself is not there in the system. So, returning null for getAddress() is semantically the right thing to do. I was surprised and when i checked the hibernate documentation it was even mentioned there that if all properties of a component are null, then the component itself is considered null.

In another situation this could have been bad, I don’t know, but for my purpose I was happily surprised with this nice touch from hibernate. These kind of small things is what differentiates a great product from a good product. Ain’t it?

Final Modifier for method arguments. What do you think? January 2nd, 2010

The IT industry today is sodden with TLAs like SOA, ESB… and FLAs like AJAX, SOAP and JUNK. i was thinking about refreshing myself with some fundamentals again. Blogging about a basic concept may not be cool, but refreshing – don’t you think? I know what you are thinking. You are thinking that i am digressing too much. Ok, lets cut to the chase.

One of the best practices i follow religiously is to use final modifiers for method arguments where applicable. This is “supposedly” a best-practice written by somebody somewhere. Regardless of whether it is documented as a best-practice or not it is an important concept to understand and use. I have 2 valid reasons to use them for my method arguments.

First, final variables cannot be modified. Come on, everybody knows that. Maybe, but its use is significantly enhanced when it is a method argument and more importantly when you are in a big team environment.

Lets assume that a method takes List as its argument. Typically, the intention of that method is to work with the List – add to it, remove elements from it, use its elements in some way, sort it and what not. Consequently when the method returns, the caller can investigate the passed List and work with the modifications the callee introduced. But the caller will be on for a big surprise if the callee changes the instance that reference points to itself.

We know that java uses “Pass by copy of reference”. If the callee points the received reference to a different List and then modifies this List, the caller will not be able to see any change at all. This is because the copy of the reference held by the caller still points to the same old List. More often than not this is done by mistake and is not intentional. If such a behavior is intentional, final modifier is not required. In all other cases since this leads to bugs in code, it is a good practice to use final modifier for method arguments.

Second, if the method uses the infamous anonymous inner-class syntax to do something, and that inner class wants to use the methods arguments, java requires those arguments to be declared final. This is more of a rule than a valid reason.

Are there more valid reasons? I will be glad to receive information from you guys.

Hibernate: Why should I Force Discriminator? August 26th, 2009

Hibernate is an ambitious project that aims to be a complete solution to the problem of managing persistent data in java. Even with such an arduous task before them, the hibernate team tries very hard to expose a simple API for developers like us. Still, the complexity behind the API shows its ugly face time and again and I believe it is unavoidable as long as the mismatch between Object and Relational world exists.

That said, although I have worked with hibernate for many years and have been its advocate in all my organizations, I keep facing newer issues and keep finding newer ways to work with it efficiently and effectively. Recently, when I was working for nboomi.com, I faced an issue when mapping a OneToMany relationship to the sub-classes of “Single Table Inheritance” strategy. After a frustrating couple of hours of debugging I finally landed on the correct solution. So, I thought other developers who will travel this path could get benefited and started writing this blog post.

Let me explain the issue I faced with an example. Assume you have a normal User Entity with the typical id, version and loginId properties. Assume this User can have many AboutUs sections and many Service sections. You don’t need to be an architect to model them as OneToMany relationships from User. So, I modelled UserAboutSection and UserServiceSection entities and created a OneToMany relationship between User and these entities. Looking at the commonality between these two, I decided to factor out the common fields into a superclass called UserSection. Now, both UserAboutSection and UserServiceSection extends UserSection. I chose to map this Inheritance hierarchy using “Single Table Inheritance” strategy to keep it simple and since most of the fields were common and only a few were specific.

The User entity is given below. Notice the List<UserAboutSection> and a List<UserServiceSection> mapped using OneToMany relationship.

The getters, setters, adders, imports and static imports are omitted for brevity.

@Entity @Table(name = "user")
public class User extends BaseEntity {

    @Column(name = "login_id")
    private String loginId;

    @Column(name = "password")
    private String password;

    ...

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserAboutSection> aboutUs;

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserServiceSection> services;

    ... Getters, Setters and Adders
}

Here goes the UserSection entity that acts as the base class in this “Single Table Inheritance” strategy. Hibernate uses the @DiscriminatorColumn annotation to distinguish between sub-classes.

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING)
public class UserSection extends BaseEntity {

    @Column(name = "title")
    protected String title;

    @Column(name = "description")
    protected String description;

    ... Getters and Setters
}

Here goes the UserAboutSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("ABOUT")
public class UserAboutSection extends UserSection {
    @ManyToOne
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserAboutSection
}

Here goes the UserServiceSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("SERVICE")
public class UserServiceSection extends UserSection {
    @ManyToOne
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserServiceSection
}

Pretty straightforward… huh! When you try to retrieve an instance of User along with its aboutUs and services collections eagerly (or lazily – doesn’t matter), what do you expect?

I expected an instance of User with the aboutUs collection filled with only UserAboutSection instances and the services collection filled with only UserServiceSection instances corresponding to only the rows they represent in the database. And I believe this expectation is valid, because that is what the mapping looks like and hibernate also has all the information it needs to make this work.

But I got something different. Both the aboutUs and services collections had all the UserSection rows that belong to this User. I mean, aboutUs collection had all the UserSection instances including UserAboutSection and UserServiceSection instances. This was surprising because hibernate has all the information it needs to populate the right instances.

After quite a bit of debugging, googling and RTFM-ing I landed upon @ForceDiscriminator annotation. This annotation has to be applied to the base class in the Inheritance hierarchy for “Single Table Inheritance” strategy. In my case, I had to apply it to UserSection entity. The UserSection entity after applying this annotation is given below…

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING)
@ForceDiscriminator
public class UserSection extends BaseEntity {

    @Column(name = "title")
    protected String title;

    @Column(name = "description")
    protected String description;

    ... Getters and Setters
}

Once I ask hibernate to Force Discriminiator, it is happy and populates the aboutUs and services collections with its respective instances.

Ok, Problem Solved! But why did I have to tell hibernate to Force Discriminator. Shouldn’t that be the default behaviour. Is it a bug in hibernate or is it a feature? Am I missing something? If any one of you hibernate fans have walked this path and know the answer, please feel free to drop in a comment. I sincerely hope this post will be a valuable time-saver for other hibernate developers who step on this Bug/Feature.

Is it an AJAX Request or a Normal Request? June 27th, 2009

In modern web application development, many a times you would want to know if the incoming HTTP Request is an AJAX request or just a Normal request. Have you come across this requirement? I have, and the solution that I found turned out to be pretty straight-forward and I will be sharing it with you here.

Whenever an AJAX request is sent to the server, a special header named X-Requested-With with a value of XMLHttpRequest is attached to the request. So, a simple check to see whether the X-Requested-With header has a value of XMLHttpRequest solves the challenge. An example will give you more clarity. Take a look at the examples of isAjax() methods in two famous server-side programming languages – Java and PHP.

Java:

public static boolean isAjax(request) {
   return "XMLHttpRequest"
             .equals(request.getHeader("X-Requested-With"));
}

PHP:

function isAjax() {
   return (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
              &&
            ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}

From the code above, it should be clear that if the method returns true, then you received an AJAX request. If the method returns false, you received a Normal HTTP Request.

Now you know how to find out if it is an AJAX request or not. But how is it useful? What do you do with it?

Have you heard of the term Unobtrusive javascript. Come on, It is a buzzword these days. There is a lot to writing Unobtrusive javascript code, but one of its features – Progressive Enhancement – stands out from the rest. Again, let me explain this with an example.

Let us assume that you have designed a beautiful looking web page with tabbed navigation. Being a hard-core AJAX fan and an efficiency aficionado you don’t like to bring back a full page with the headers and the footers and the sidebars when your user clicks on a Tab. Instead you would love to bring back only the content area for the tab via AJAX and innerHTML it into its respective place. Correct? The good programmer inside you has also told that you should not hard-code the URL for the AJAX call in your javascript. Instead, your tab should be designed as an anchor whose href attribute points to the URL for the content. So far so good? Now, when the user clicks on the Tab, you collect the URL from its href attribute and fire an AJAX call to the server. The server obediently accepts the request and sends back the content just for the active tab.

<ul>
   <li><a href="/tab1.page" rel="#tab1">Tab 1</a></li>
   <li><a href="/tab2.page" rel="#tab2">Tab 2</a></li>
   <li><a href="/tab3.page" rel="#tab3">Tab 3</a></li>
</ul>

<div>
   <div id="tab1">Content for Tab1</div>
   <div id="tab2"> Content for Tab2 </div>
   <div id="tab3"> Content for Tab3 </div>
</div>

You would like to believe that all is well and good… Unfortuntately this is where the challenge of Progressive Enhancement begins. How do you plan to support browsers with JavaScript disabled. Yes, there are quite a few people who still do that for the fear of script related worms. How do you plan to support automated bots? Don’t you want the Google bots and the Yahoo bots to index all your pages with full content? Do you know what these users will see? They will see a half-baked page with just the active tab’s content and no styles – not even the header, footer or the sidebar. I am sure you don’t want this to happen. That is when the isAjax() method comes useful.

Whatever you did on the client side – HTML, CSS and javascript – is great and perfect. You separated the behavior from style and markup. So, you don’t have to touch it. You just need to do a small bit of work on the server-side.

In our case, when JavaScript is disabled, the browser will take over and execute its default behaviour of firing a Normal request to the URL specified in the href attribute. When JavaScript is enabled, JavaScript will take over and will fire an AJAX request to the same URL. In both cases the same server-side resource (like in Java or PHP) will receive the request. Now that you have decided to support Progressive Enhancement, you will have to check if the incoming request is an AJAX request or a Normal request using the isAjax() method shown earlier. In case of an AJAX request, you will send back only the content area of the tab thereby providing an efficient version of your application to JavaScript enabled users. In case of a Normal request, you will send back an entire page including the tab’s content, thereby providing a less efficient yet fully functional version of your application to JavaScript disabled users.

// Pseudo Code
if(isAjax(request) {
   return "Content area for the tab";
} else {
   return "Full page including tab content";
}

Now you can feel proud that you are not one of those who just talk about Unobtrusive JavaScript but you are one of those who have implemented it. I sincerely hope this article was useful. Feel free to drop in a comment with suggestions and/or feedback.

Update 1:

Based on the input provided by a buddy called Sabob from dzone, X-Requested-With is set only by AJAX libraries like jQuery, Mootools, Prototype etc. If you are coding AJAX by hand, then you will have to explicitly set this header while sending a request. More importantly you should somehow abstract it using good OO principles so that you don’t have to explicitly code this line every time you send an AJAX request.

Show time! – First ever Amazon EC2 Success Stories February 5th, 2007

Amazon, always an innovator, recently unfolded yet another masterpiece to the world in the form of EC2 web-service. Gumiyo.com, an online mobile-commerce provider and Abaca.com, a spam-blocker solution, are now celebrated as the pioneers to launch a production site using Amazon EC2 Service. You can relish the full versions of their success stories here and here.

EC2 (Elastic compute cloud) – the name doesn’t tell much, or does it? For those who are not familiar, EC2 is a dynamically scalable data-center kind of service. It is not a REST/SOAP style web-service that we have come to conventionally recognize. We do not fire a call, and expect a response. Instead, we get access to virtual servers equivalent of Intel Xeon 1.7 GHz, 1.75 GB of RAM, 250 MB/S of network bandwidth and 160 GB of local hard drive space. Any number of such servers are at our disposal in just a matter of minutes, and that my friends, is not just innovative, but a killer idea in the data-center services arena. At 10 cents per hour of instance up-time, this service is something any start-up, if not individuals, should seriously consider. An EC2 account implicitly comes with a S3 account. Of course you can sign-up for S3 separately as well. In case you are wondering what S3 is, keep reading…

S3 (Simple Storage Service) is, well, a simple storage service that can be used to store and retrieve huge volumes of data over the internet. This offering has a similar accent to traditional web-services. The infamous REST and SOAP interfaces are provided for campers at both ends of the web-services campground. The value-add I see in this service is Simplicity, Cost effectiveness and more importantly, the trust that we already have over Amazon’s infrastructure. After all, they are one of the very few survivors of the DotCom boom. At 15 cents for a GB of storage per month and 20 cents for a GB of data transfer, S3 is something that i would use for all my back-up needs. Being a java programmer, I use the JetS3T library from Java.net and see how easy it gets…

// Sample code that uploads a file to S3.
String access = "YOUR_AWS_ACCESS_KEY";
String secret = "YOUR_AWS_SECRET_KEY";
AWSCredentials cred = new AWSCredentials(access, secret);

// I used Rest, you could use Soap
S3Service s3 = new RestS3Service(cred);

// Buckets are like folders, but globally unique
S3Bucket bucket = s3.createBucket(access + ".Test");

// File that you want to upload
File file = new File("SomeFile.txt");

// Upload your file
S3Object s3Object = new S3Object(fileData);
object = s3.putObject(bucket, file);

Start-ups, small businesses and web 2.0 companies should regard these services as “God-Sent”. Well, I guess, I am not wrong. Two startups have already considered it serious enough to launch their production environment on EC2. And I’m sure there are more to come. Lets see what they are up to.

Gumiyo.com is the first end-to-end mobile commerce platform, connecting live buyers and live sellers through mobile phones and through the Web. Using any mobile phone with a built-in camera and a basic data plan you can create ads in 3 easy steps

1. Capture images or video of an item
2. Attach them to a multimedia message with a short description
3. Send it to post [AT] gumiyo [DOT] com

Gumiyo will create an online ad for you and then send you a reply link asking you to review and edit your ad before it is posted. You don’t need to use a mobile phone though. You can login and place your ad any time on the Web. You can even send them your ad as an email with photo or video attachments. Could it get any easier? Check it out for yourself.

Abaca.com is a spam-blocker appliance that you can purchase for under $2000. This email protection gateway offers 99% guaranteed filtration with zero management. At present, I don’t have a need for such an appliance as an individual. So, I didn’t try it out myself.

Will more and more businesses build around these services? Will traditional data-center providers offer EC2 as an option with GUI based configuration? Will amazon create more like these? What do you think?

Hibernate – Difference between session’s get() and load() January 16th, 2007

Being an avid hibernate fan, I have always defended it in my organization when people throw undue criticism at it in order to protect themselves. In one such debate, a colleague pointed out a pattern in our code-base that introduced needless performance degradation, and condemned hibernate for it. I was glad he brought that up – for 2 reasons. First because, it sure was a problem and called for immediate attention. Second because, once again the problem was not with hibernate, but us. If you look closely at domain driven applications, you will notice that a few core objects are directly referenced by most other objects. Let me clarify what i mean with an example. In an auction application, for example, an Auction is held for an Item, a Bid is placed for an Item, a Buyer buys an Item. The common object referenced here is, well, an Item. This implies that whenever you create a new Auction or Bid you are constrained to supply a reference to Item. The most obvious way to achieve this is by getting a persistent instance of Item from the database using the session.get() method. This works, but it has its limitations.

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

Item item = (Item) session.get(Item.class, itemId);

if(item != null) {
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} else {
   // Handle the error condition appropriately
   log.error("Bid placed for an unavailable item");
}

Think about it… How many times will a bid be placed for an Item? Many… Every time a Bid is placed, is it wise to hit the database and retrieve the corresponding Item just to supply it as a reference? I guess not. That is where session.load() comes in. All the above scenarios remaining the same, if you just used session.load() instead of get(), hibernate will not hit the database. Instead it will return a proxy, or an actual instance if it was present in the current session, and that can be used to serve as a reference. What does this buy you? At least 2 advantages. First, you save a trip to the database. Second, the error handling code just got elegant. Take a look at the code snippet below. Here we don’t handle erroneous conditions using null checks. Instead we use exceptions, which sounds appropriate in this scenario. Don’t they?

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

try{
   Item item = session.load(Item.class, itemId);
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} catch(ObjectNotFoundException e) {
   // Handle the error condition appropriately
   log.error("Bid placed for an unavailable item");
}

From the above piece of code, it is obvious that, an ObjectNotFoundException may be thrown if the actual Item representing the given item id cannot be found. What i am not clear about – and neither is hibernate documentation – is which method is more likely to cause this exception and why? session.load() seems to have a possibility to throw this exception, and so does saveOrUpdate() for the same fact that item for the given id/proxy is not available. I would love to hear from people who have traveled this path and have an answer. Also, it would be wonderful, if you could point out other differences between session.get() and load() that i may have missed.