Dear All,
First off: Hibernate is excellent. I'm really very impressed. Thank you.
My problem: I have a really nice object model that I am loath to compromise too much for the sake of database persistance. I'm using an
inner class which implements a public interface.
Basically, I want hibernate to set up this inner class with data from the database, but obviously hibernate can't create the inner class directly.
Now, the enclosing class can do the construction before hand without a problem, and then just have hibernate plug in values via the public interface. Except that I can't see how to stop hibernate trying to create the pojo itself. Here's a code example..
Public Interface
Code:
public interface IWalk {
public void setSpeed(int speed);
public int getSpeed();
public void start();
}
Implementing Class(s)Code:
public class Cat {
private IWalk _walker;
public Cat() {
super();
_walker = new CatWalker();
}
protected void setWalker(IWalk walker) { _walker = walker; }
protected IWalk getWalker() { return _walker; }
protected class CatWalker() implements IWalk {
private int _speed;
public void setSpeed(int speed) { _speed = speed; }
public int getSpeed() { return _speed; }
public void start() {
//cat specific walking code
}
}
}
Current WorkarroundRight now, what I've done is to insert another superclass for the walker which
can be constructed by hibernate and then implement an
assignFrom function to copy the values over. I'll show you, but be warned; It's ugly.
Code:
public abstract class WalkerBaseClass implements IWalk {
public WalkerBaseClass() { super(); }
public void assignFrom(IWalk walker) {
setSpeed(walker.getSpeed());
//imagine 10+ other set(get()) combinations here.
}
}
...and then in the Cat class....Code:
public class Cat {
private IWalk _walker;
public Cat() {
super();
_walker = new CatWalker();
}
protected void setDBWalker(IWalk tempWalker) {
_walker.assignFrom(tempWalker);
}
protected IWalk getDBWalker() {
WalkerBaseClass tempWalker = new WalkerBaseClass();
tempWalker.assignFrom(_walker);
return tempWalker;
}
protected IWalk getWalker() { return _walker; }
protected void setWalker(IWalk walker) { _walker = walker; }
protected class CatWalker() extends WalkerBaseClass {
private int _speed;
public void setSpeed(int speed) { _speed = speed; }
public int getSpeed() { return _speed; }
public void start() {
//cat specific walking code
}
}
}
As I said, it's ugly, breaks my encapsulation (although I could make the getter/setters private) and makes the code hard to read. I suppose it's a type of Momento pattern which is a traditional database persistance strategy and just plain inferior to the Hibernate method. I have used this inner-class-implementing-interface patern quite a lot and would really appreciate a better strategy for persistance.
Any syggestions?
Regards,
Ben Hathaway.
Notes:
Hibernate Version: 3.1.3
Database: HSQLDB 1.8.0.4
[/b]