I have two java classes, A & B, with A holding a reference to B:
public class A {
private long id;
private B b;
...
}
public class B {
private long id;
...
}
In my database only instances of A are stored, alongside with the ID of the referenced B’s:
$ select * from tableA;
id | bid | ...
---------------
1 | 42 |
2 | 42 |
3 | 43 |
...
However, B are not stored in the database, but accessible through some implementation of a service layer ServiceB:
public interface ServiceB {
public B getB(long bid);
}
How can I model that using Hibernate? I’d preferably use an XML-based HBM configuration. I also would like to avoid adding a transient field in A holding bid (if it is possible).
I’m posting here the solution found for reference.
You have to create a custom hibernate
UserTypewhich is used on the mapping for thebidfield inAclass. ImplementingUserTypeis already well explained on Internet and is not the point here. Suffice to say that thenullSafeGet()operation convert the database id to a B instance by loading the corresponding B from the service layer; and thenullSafeSet(), the other way around, convert a B instance to it’s internal id to store to the database.Linking this custom user type to the service layer can be done several ways depending on the injection framework used (Guice, Spring, custom solution…) but should not be a problem.
You need a custom
UserTypefor each referenced classB. Using generics may be useful in the case of several referenced classes deriving from a common base class, it’s left as an exercise to the reader.