I am trying to map a normalized Java model to a legacy database schema using Hibernate 3.5. One particular table encodes a foreign keys in a one-to-many relationship as a bit array column.
Consider tables person
and club
that describes people's affiliations to clubs:
person: .----.------. club: .----.---------.---------------------------.
| id | name | | id | name | members | binary(members) |
|----+------| |----+---------|---------+-----------------|
| 1 | Bob | | 10 | Cricket | 0 | 000 |
| 2 | Joe | | 11 | Tennis | 5 | 101 |
| 3 | Sue | | 12 | Cooking | 7 | 111 |
'----'------' | 13 | Golf | 3 | 100 |
'----'---------'---------'-----------------'
So hopefully it is clear that person.id
is used as the bit index in the bit array club.members
:
.---.---.---.
| S | J | B |
| u | o | o |
| e | e | b |
|---+---+---|
| 1 | 0 | 1 |
'---'---'---'
In this example the members
column tells us that:
- no one is a member of Cricket --- no flags set
- Bob/Sue -> Tennis --- flags at positions 1 and 3 are set
- Bob/Sue/Joe -> Cooking --- flags at positions 1, 2 and 3 are set
- Sue -> Golf --- flag at position 3 is set
Now, for this example a join table could've been used instead which would simplify matters and avoid many potential issues - e.g: the maximum range of members
placing an upper bound on the number of people
rows. However, I am stuck with this schema and it seems that there were factors in favour of using a bit array column way back when.
In my Java domain I'd like to model this schema with entities like so:
class Person {
private int id;
private String name;
...
}
class Club {
private Set<Person> members;
private int id;
private String name;
...
}
I am assuming that I must use a UserType
implementation but have been unable to find any examples where the items described by the user type are references to entities - not literal field values - or composites thereof. Additionally I am aware that I'll have to consider how the person
entities are fetched when a club
instance is loaded.
Can anyone tell me how I can tame this legacy schema with Hibernate?