tags:

views:

286

answers:

2

Setting: I have an object (AProduct) persisted by hibernate in my database. This object references another object (AComponent) stored in a repository. In the database table of the product only the ID of the component should be stored. By loading the product, I want to load the correct component from my repository.

My solution so far is to create a UserType for the component to save only its ID. So far it's easy. Loading the component is also not the big deal because I have the ID.

My problem is how to get a link to the repository in ComponentUserType.

I am using java and Hibernate/Annotations but the solution might be independent.

A: 

By "repository" I assume you mean some external source of data other than the database. A web service or something? Anyway, if the link to the repository is static configuration that is the same for all product objects, you could create a singleton object with a static accessor method (e.g. "getInstance()") to hold the configuration. The UserType object could then pull the repository configuration from the singleton. If you're using a dependency injection framework like Spring, you could even use it to initialize the singleton from a property file or something. An even better alternative would be to use Spring (or Guice or whatever) to push the configuration directly into the UserType. But since UserType object lifecycles are controlled by Hibernate, that could be tricky.

If the repository link is different for each product, then it makes sense to save it in the database along with the ID. One way to do this is to create a class that encapsulates the ID-repository pairing as well as the reference to the component. Then use that class as the property type in your product class, and have the Hibernate UserType map that class to a couple of columns to hold the ID and the link, respectively.

Rob H
A: 

Are you using Spring Framework to initialize your application stack? If so, check out the SingletonBeanFactoryLocator, it will help you get to your application resources in a Spring-friendly manner.

http://www.jdocs.com/spring/2.0.6/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.html

If you're not using Spring, I would look into using a ThreadLocal exposed from a static class somewhere in your application stack. You will need to ensure your Repository is bound to the ThreadLocal prior to being used with your UserType.