views:

267

answers:

1

Is there a sleek way to map a default database object in Hibernate?

For example, in this class, a Foo should always be able to return a Bar, whether it's custom defined for the Foo, or it comes from a default value that's stored in the database somewhere. Users of Foo should be able to set a custom Bar object in it, but they don't need write access to Bar - hence the reduced visibility. :

public Class Foo {
    public Bar Bar {
        get {
            return CustomBar ?? DefaultBar;
        }
    }

    public Bar CustomBar { get; set; }
    protected Bar DefaultBar { get; private set; }
}

The thing I'm wondering about is how to hibernate map that DefaultFoo property. All the Bar classes should be able to get to that single DefaultFoo object. The only way I know how to do this in Hibernate is with a one-to-many mapping in Foo. (Foo containing one to many Bars)...this seems a little kludgy, since there's always at most one Bar. Is there a better pattern for this type of behavior? TIA.

A: 

This is also called the NullObject or DefaultObject pattern. There has been some discussion on the Hibernate mailing lists about this. But I haven't seen anything about how you would actually store it in the database. If you want a real NullObject, external of the Database, then you can implement a Singleton default object and implement the ILifecycle interface (I think) and veto the OnSave event to prevent it from being persisted.

geofflane