NHibernate
Posts related to NHibernate
NHibernate 2.0 GA released!

Per Fabio's Post, NHibernate 2.0 has been released:

NHibernate 2.0.0.GA is released today
https://sourceforge.net/project/showfiles.php?group_id=73818&package_id=73969
Enjoy it!
We start the work for NH2.0.0SP1
~20 days to:
- support parameters in HQLFunctions
- minors change in tests
- improv for some dialects
- some other minors
And we hope nothing tremendous happen ;)
Bye.
Fabio Maulo
The human knowledge belong to the world

Go grab the download and upgrade today! :)

-Brian Chavez

Add Comment Filed Under [ NHibernate ]
Differences between NHibernate FetchMode.Eager and FetchMode.Join

What are the differences between FetchMode.Eager and FetchMode.Join?  There are none!  According to the Java Hibernate docs, FetchMode.Eager and FetchMode.Lazy have been deprecated.

In NH 1.2.1 GA source code, this is how FetchMode is defined:

   15     [Serializable]
   16     public enum FetchMode
   17     {
   18         /// <summary>
   19         /// Default to the setting configured in the mapping file.
   20         /// </summary>
   21         Default = 0,
   22         /// <summary>
   23         /// Fetch eagerly, using a separate select. Equivalent to
   24         /// <c>fetch="select"</c> (and <c>outer-join="false"</c>)
   25         /// </summary>
   26         Select = 1,
   27         /// <summary>
   28         /// Fetch using an outer join.  Equivalent to
   29         /// <c>fetch="join"</c> (and <c>outer-join="true"</c>)
   30         /// </summary>
   31         Join = 2,
   32 
   33         Lazy = Select,
   34         Eager = Join
   35     }

Well, now that clears up some of my confusions... confused0078.gif

2 Comments Filed Under [ NHibernate ]
Visitor Pattern for User Interface and Display

I was browsing the NHibernate forums and came across a post by "thatmikewilliams" who posted the following code:

--------------------------------------------------------

Because this functionality is closely tied to the user interface you should probably use a visitor for this (rather than an overridden method in your class hierarchy).

package test.visitor;
public abstract class Payment {
   interface Visitor {
      Object visit(CardPayment payment);
      Object visit(CashPayment payment);
   }
   public abstract Object accept(Visitor visitor);
}

package test.visitor;
public class CardPayment extends Payment {
   @Override
   public Object accept(Visitor visitor) {
      return visitor.visit(this);
   }
}

package test.visitor;
public class CashPayment extends Payment {
   @Override
   public Object accept(Visitor visitor) {
      return visitor.visit(this);
   }
}

package test.visitor;
public class PaymentDisplayStringVisitor implements Payment.Visitor {
   public Object visit(CardPayment payment) {
      return "CC";
   }
   public Object visit(CashPayment payment) {
      return "CS";
   }
}

package test.visitor;
import java.util.ArrayList;
import java.util.List;
public class Test {

   public static void main(String[] args) {
      List<Payment> payments = new ArrayList<Payment>();
      payments.add(new CashPayment());
      payments.add(new CardPayment());
      
      PaymentDisplayStringVisitor visitor = new PaymentDisplayStringVisitor();
      for (Payment payment : payments) {
         System.out.println(payment.accept(visitor));
      }
   }
}

----------------------------------------------

Using the Visitor Pattern to display domain specific types on a user interface is a nice approach instead of overriding specific methods on your domain object, on top of that, cluttering your domain objects with useless "UI" specific methods like ("get object name").  Pretty interesting approach. :)  Notice the PaymentDisplayStringVisitor returns specific string type based on the type.  Very Cool.  I'll try extending this approach using .NET and Generics and post some code later.

NHibernate - null id in entry (don't flush the Session after an exception occurs)

imageI ran into this issue today when trying to persist one of my objects.  The cause of the problem was interesting.  I was trying to save an object when a property/columns in the table had a unique constraint.  As a result, the object that I was trying to persist would not persist simply because the object's property it failed to meet the unique constraint.

As a result, a call to Save() on the object failed and the ID on the object I was trying to save was not set, but NHibernate still processed the object and associated it with its persistence mechanism leaving it in a "semi-persistent" state with the NHibernate persistence manager (ie: NHibernate now knows about the object you tried to save and it SHOULD have fully evicted the object from its persistence manager because the save failed, but it didn't).

When an HTTP request finishes on my ASP.NET application, I flush and close all NHibernate session objects at the time the request is done.  And as a result, when the HTTP request finished, NHibernate attempted to flush the jacked up "semi-persistent" object (an object who's ID was null) and ultimately generating the error above.

So, the solution that I implemented was to wrap the Save() in a try{} catch{} statement, and if the save failed, immediately close and shutdown the session, handle the error/exception.  Then, check if Session.IsOpen when the HTTP request finishes.

Hope that helps, confused0081.gif

Brian Chavez

NHibernate and Inverse=True|False Attribute

In order to truly understand the inverse attribute in NHibernate, you need to first look at your relationship from the database table point of view and how your domain objects maps into their respective tables.  It comes down to determining who is the owner of the relationship association between the parent and child objects.

Suppose you have ParentTable (parentId PK, parentcol1, parentcol2) and ChildTable(childid PK, parentid FK, childcol1, childcol2).  In a one-to-many relationship, you will have one parent and many children.  The ChildTable has a primary key and foreign key.   The foreign key is a reference to the primary key in the ParentTable.  If you look at the ChildTable, you will notice that the ChildTable stores extra information about a row in the ParentTable via the ChildTable's parentId foreign key.  Using this perspective, the "child" owns (knows about) the relationship it has with its parent row.  So, the child will be the owner of the relationship in this one-to-many relationship.

Where does inverse come in?  Well, from the Parent's perspective, since the parent doesn't own the relationship it is considered the "inverse" of the relationship.  Below is some additional information I pulled down an edited from IBM's websphere pages:

http://www.ibm.com/developerworks/websphere/techjournal/0708_vines/0708_vines.html

Many-to-one relationship

The entity declaring the many-to-one relationship is the child object (or owner of the relationship), as its table has the foreign key, while the object that is referenced by the entity declaring the many-to-one relationship is the parent object. Since its table doesn't have the foreign key, it is the non-owner, or inverse of the relationship.

Hibernate conventions

In Hibernate, many-to-one relationship maps as follows:

  • Use many-to-one element in the child class.
  • Define the primary key in the parent class.

 

One-to-many relationship

A one-to-many relationship defines a reference to a collection of objects. It is the most common kind of relationship that you will find in object models due to the fact that use cases typically require traversal from the parent object to its children, but may or may not require traversal from the child back to its parent; which means a unidirectional one-to-many relationship will suffice in most cases.

The entity declaring the one-to-many relationship is the parent object (and is the non-owner). The table for this entity defines the primary key, but it does not have the foreign key -- that is in the child.

In Hibernate, the mapping of one-to-many relationships is generally done by adding a column to the child table for the foreign key, but the details of the mapping differs depending on whether it is a unidirectional or a bidirectional one-to-many relationship.

In the unidirectional case, the foreign key column in the child table doesn't map to a property in the child object; it is in the data model, but not the object model. Since it is unidirectional there is just a property in the parent object [that contains a collection of children]; not the child [the child object does not contain any information back to the parent]. In addition, the foreign key column [in the child table] has to be defined as nullable because Hibernate will first insert the child row (with a NULL foreign key) and then update it [the inserted row] later [with the parent's primary key].

In the bidirectional case, the object-relational mapping is better because there is a property in the child object for the foreign key column, and that column doesn't have to be nullable in the database. But the resulting object model has cyclic dependencies and tighter coupling between the objects, and requires additional programming to set both sides of the relationship.

As you can see, there are several tradeoffs to consider with regard to the definition of one-to-many relationships, but using unidirectional relationships is generally recommended unless there are use cases that indicate the need for navigation in both directions.

Hibernate conventions

In Hibernate, one-to-many (unidirectional) relationships map as follows:

  • Use the set, bag, or list with one-to-many sub-element in parent class.
  • Create a foreign key in the table representing the child class if the relationship is unidirectional; otherwise, use the many-to-one relationship for a bidirectional relationship.

There are some additional features that are often used in the definition of one-to-many relationships[...]:

  • Hibernate

    • inverse="true"
      In Hibernate, you might encounter the inverse="true" attribute being used in the definition of a bidirectional relationship. If so, don't worry, because this feature is equivalent to ... the non-owner of the relationship whose table doesn't have the foreign key. Similarly, the Hibernate inverse="false" attribute is equivalent to the ... owner of the relationship whose table has the foreign key.

      In general, these notions align, except for the case where someone defines a Hibernate mapping with inverse="true" set on the many-to-one side of a bidirectional relationship. If you find such a mapping, you should change it ..., as it is not a best practice in Hibernate and does not generate optimal SQL. For instance, if the many-to-one side is set to inverse="true" then every time you create a child, Hibernate will execute two SQL statements, one to create the child and one to update the child with the foreign key of the parent. Changing it to inverse="false" on the many-to-one side and setting inverse="true" on the one-to-many side will fix that oversight ...

 

Many-to-many relationship

A many-to-many relationship defines a reference to a collection of objects through a mapping table. Many-to-many relationships are not all that common in an object model, but they will generally be bidirectional.

Like the other bidirectional relationships, there is an owning and a non-owning side. In this case, the owning side has the mapping table, instead of the foreign key. Either side can be designated as the owning side; it doesn't matter which side you pick.

Hibernate conventions

In Hibernate, many-to-many relationship maps as follows:

  • The non-owner uses the collections (set, bag, or list) element with the inverse="true" attribute, the table attribute, the key sub-element, and the many-to-many sub-element.
  • The owner of the relationship uses the collections (set, bag, or list) element with the table attribute, the key sub-element, and the many-to-many sub-element.
19 Comments Filed Under [ NHibernate ]