Paul

Tuesday Feb 05, 2008

Implicate Polymorphism in Hibernate

Implicate polymorphism in hibernate is the ability to query on a superclass or interface and return a collection that is a mix of all of the sub classes or implementations that meet those criteria from several tables.
For example, lets say you have the following two domain objects:

public class Person
{
     private String firstName;
     private String lastName;
     private String phoneNumber;

     //getters and setters
}

public class Business
{
     private String name;
     private String phoneNumber;
     
     //getters and setters
}

If you notice, both of the above classes have a phone number. Lets say I wanted to do a search for anything with the phone number of 515-555-8745. The most obvious way would be to have a method in your service layer that calls the DAOs for both tables and combines the result.
With implicate polymorphism I can create a HasPhoneNumber interface with a getter and setter for phone number like this:
public interface HasPhoneNumber
{
     public String getPhoneNumber();
     public void setPhoneNumber(String phoneNumber);
}

I implement this interface on both objects. No special mapping is required. Now when i run an HBM query like this "from HasPhoneNumber x where x.phoneNumber=?" i will get a Collection that is a mix of both Business and Person objects.
As an added bonus. If I modify one of these objects and save it, It will automatically save it to the correct table.
For more information on this and other kinds of inheritance mapping visit http://www.hibernate.org/hib_docs/reference/en/html/inheritance.html

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed

Calendar

Feeds

Search

Links

Navigation

Referrers