<?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>Ganesh &#187; Hibernate</title>
	<atom:link href="http://www.gmarwaha.com/blog/category/serverside/hibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gmarwaha.com/blog</link>
	<description>Ganesh\</description>
	<lastBuildDate>Mon, 01 Mar 2010 13:58:37 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Hibernate never stops surprising me</title>
		<link>http://www.gmarwaha.com/blog/2010/02/28/hibernate-never-stops-surprising-me/</link>
		<comments>http://www.gmarwaha.com/blog/2010/02/28/hibernate-never-stops-surprising-me/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 13:53:31 +0000</pubDate>
		<dc:creator>Ganeshji Marwaha</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Server Side]]></category>

		<guid isPermaLink="false">http://www.gmarwaha.com/blog/?p=141</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>I have a simple form in my web application where a user can fill in his personal details and address details. <em>User</em> specific fields include firstName, middleName and lastName while <em>Address</em> specific fields include street, city and zip. On the server side, I have POJOs for <em>User</em> and <em>Address</em>. Finally I use <a href="http://www.hibernate.org">Hibernate</a> to map these POJOs to the database.  Since, the <em>Address</em> will not be used outside the context of the <em>User</em>, I decided to map it as a Component of the <em>User</em> class. </p>
<p>The <em>User</em> class and its corresponding mapping is given below:</p>
<pre>
@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
}
</pre>
<p>The <em>Address</em> class is mapped to <em>User</em> as a component. You can see the specifics of the mapping below.</p>
<pre>
@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
}
</pre>
<p>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 <em>Component</em> mapping, I recently stepped on an interesting Feature (or it could be an Issue) and I was happily surprised by it.</p>
<p>Want to know the surprise? Keep reading&#8230; </p>
<p>In this case you map an <em>Address</em> as a value type using <em>@Embedded</em> annotation in the &#8220;homeAddress&#8221; field of the <em>User</em> class. The <em>Address</em> class itself is declared to be <em>@Emeddable</em>. 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&#8217;s table. Now, when you insert an instance of <em>User</em> into the database, while specifying all null values for <em>Address</em>&#8217;s fields maybe because the user didn&#8217;t give his address, then what would you expect in return at some point in time when you retrieve this <em>User</em> back from the database. </p>
<p>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&#8217;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. </p>
<p>In another situation this could have been bad, I don&#8217;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&#8217;t it?</p>
<div class="hypeIt"><script type="text/javascript">var dzone_url = 'http://www.gmarwaha.com/blog/2010/02/28/hibernate-never-stops-surprising-me/';</script><script type="text/javascript">var dzone_style = '2';</script><script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script></div>
]]></content:encoded>
			<wfw:commentRss>http://www.gmarwaha.com/blog/2010/02/28/hibernate-never-stops-surprising-me/feed/</wfw:commentRss>
		<slash:comments>51</slash:comments>
		</item>
		<item>
		<title>Hibernate: Why should I Force Discriminator?</title>
		<link>http://www.gmarwaha.com/blog/2009/08/26/hibernate-why-should-i-force-discriminator/</link>
		<comments>http://www.gmarwaha.com/blog/2009/08/26/hibernate-why-should-i-force-discriminator/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 12:40:00 +0000</pubDate>
		<dc:creator>Ganeshji Marwaha</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Server Side]]></category>

		<guid isPermaLink="false">http://www.gmarwaha.com/blog/?p=100</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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 <a href="http://www.nboomi.com">nboomi.com</a>, I faced an issue when mapping a <em>OneToMany</em> relationship to the sub-classes of <em>&#8220;Single Table Inheritance&#8221;</em> 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.</p>
<p>Let me explain the issue I faced with an example. Assume you have a normal <em>User</em> Entity with the typical <em>id</em>, <em>version</em> and <em>loginId</em> properties. Assume this <em>User</em> can have many <em>AboutUs</em> sections and many <em>Service</em> sections. You don&#8217;t need to be an architect to model them as <em>OneToMany</em> relationships from <em>User</em>. So, I modelled <em>UserAboutSection</em> and <em>UserServiceSection</em> entities and created a <em>OneToMany</em> relationship between <em>User</em> and these entities. Looking at the commonality between these two, I decided to factor out the common fields into a superclass called <em>UserSection</em>. Now, both <em>UserAboutSection</em> and <em>UserServiceSection</em> extends <em>UserSection</em>. I chose to map this Inheritance hierarchy using &#8220;Single Table Inheritance&#8221; strategy to keep it simple and since most of the fields were common and only a few were specific. </p>
<p>The <em>User</em> entity is given below. Notice the <em>List&lt;UserAboutSection&gt;</em> and a <em>List&lt;UserServiceSection&gt;</em> mapped using <em>OneToMany</em> relationship.</p>
<p>The getters, setters, adders, imports and static imports are omitted for brevity.</p>
<pre>
@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&lt;UserAboutSection&gt; aboutUs;

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

    ... Getters, Setters and Adders
}
</pre>
<p>Here goes the <em>UserSection</em> entity that acts as the base class in this &#8220;Single Table Inheritance&#8221; strategy. Hibernate uses the @DiscriminatorColumn annotation to distinguish between sub-classes. </p>
<pre>
@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
}
</pre>
<p>Here goes the <em>UserAboutSection</em> entity that derives from the <em>UserSection</em> entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.</p>
<pre>
@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
}
</pre>
<p>Here goes the <em>UserServiceSection</em> entity that derives from the <em>UserSection</em> entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.</p>
<pre>
@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
}
</pre>
<p>Pretty straightforward&#8230; huh! When you try to retrieve an instance of <em>User</em> along with its <em>aboutUs</em> and <em>services</em> collections eagerly (or lazily &#8211; doesn&#8217;t matter), what do you expect? </p>
<p>I expected an instance of <em>User</em> with the <em>aboutUs</em> collection filled with only <em>UserAboutSection</em> instances and the <em>services</em> collection filled with only <em>UserServiceSection</em> 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. </p>
<p>But I got something different. Both the <em>aboutUs</em> and <em>services</em> collections had all the <em>UserSection</em> rows that belong to this <em>User</em>. I mean, <em>aboutUs</em> collection had all the <em>UserSection</em> instances including U<em>serAboutSection</em> and <em>UserServiceSection</em> instances. This was surprising because hibernate has all the information it needs to populate the right instances. </p>
<p>After quite a bit of debugging, googling and RTFM-ing I landed upon <em>@ForceDiscriminator</em> annotation. This annotation has to be applied to the base class in the Inheritance hierarchy for &#8220;Single Table Inheritance&#8221; strategy. In my case, I had to apply it to <em>UserSection</em> entity. The <em>UserSection</em> entity after applying this annotation is given below&#8230; </p>
<pre>
@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
}
</pre>
<p>Once I ask hibernate to Force Discriminiator, it is happy and populates the aboutUs and services collections with its respective instances. </p>
<p>Ok, Problem Solved! But why did I have to tell hibernate to Force Discriminator. Shouldn&#8217;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. </p>
<div class="hypeIt"><script type="text/javascript">var dzone_url = 'http://www.gmarwaha.com/blog/2009/08/26/hibernate-why-should-i-force-discriminator/';</script><script type="text/javascript">var dzone_style = '2';</script><script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script></div>
]]></content:encoded>
			<wfw:commentRss>http://www.gmarwaha.com/blog/2009/08/26/hibernate-why-should-i-force-discriminator/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Hibernate &#8211; Difference between session&#8217;s get() and load()</title>
		<link>http://www.gmarwaha.com/blog/2007/01/16/hibernate-difference-between-sessions-get-and-load/</link>
		<comments>http://www.gmarwaha.com/blog/2007/01/16/hibernate-difference-between-sessions-get-and-load/#comments</comments>
		<pubDate>Tue, 16 Jan 2007 07:30:00 +0000</pubDate>
		<dc:creator>Ganeshji Marwaha</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://gmarwaha.com/blog/?p=4</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Being an avid <a href="http://www.hibernate.org">hibernate</a> 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 &#8211; 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 <a href="http://caveatemptor.hibernate.org">auction</a> 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 <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#get%28java.lang.Class,%20java.io.Serializable%29">session.get()</a> method. This works, but it has its limitations.</p>
<pre>
Session session = &lt;&lt; Get session from SessionFactory &gt;&gt;
Long itemId = &lt;&lt; Get the item id from request &gt;&gt;

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");
}</pre>
<p>Think about it&#8230; How many times will a bid be placed for an Item? Many&#8230; 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 <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#load%28java.lang.Class,%20java.io.Serializable%29">session.load()</a> 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&#8217;t handle erroneous conditions using null checks. Instead we use exceptions, which sounds appropriate in this scenario. Don&#8217;t they?</p>
<pre>
Session session = &lt;&lt; Get session from SessionFactory &gt;&gt;
Long itemId = &lt;&lt; Get the item id from request &gt;&gt;

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");
}</pre>
<p>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 &#8211; and neither is hibernate documentation &#8211; 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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gmarwaha.com/blog/2007/01/16/hibernate-difference-between-sessions-get-and-load/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
	</channel>
</rss>
