Assume you have two entities: User
and Decision
.
You want to associate a list of users to each decision, so you add a @OneToMany
relation in the Decision
class.
This will create a join table which could look something like
|decisionId| userId |
|----------|--------- |
|1 | 2 |
|1 | 3 |
|1 | 5 |
|1 | 6 |
|1 | 8 |
|1 | 9 |
|2 | 1 |
|2 | 3 |
|2 | 7 |
|3 | 5 |
|3 | 7 |
|3 | 8 |
|3 | 9 |
Here comes the tricky thing. I need to associate a "new" value to each association above. This is, for every user in the list of users of a decision, I want to store another value (a double in this case) with the "weight" of that User
in that Decision
.
As a first approach, I was creating a new class Voter
which had only a User
and a weight
properties, and add a @OneToMany
relation to Voter
instead of User
in the Decision
class.
However, this would result in two tables: The join table, and a Voter
entities table.
|decisionId| voterId | |voterId | userId | weight
|----------|--------- | |---------|---------|----------
|1 | 1 | |1 | 2 | 10.2
|1 | 2 | |2 | 3 | 2.7
|1 | 3 | |3 | 5 | 8.1
|1 | 4 | |4 | 6 | 20.1
|1 | 5 | |5 | 8 | 15.6
|1 | 6 | |6 | 9 | 11.2
|2 | 7 | and |7 | 1 | 52.6
|2 | 8 | |8 | 3 | 84.2
|2 | 9 | |9 | 7 | 84.3
|3 | 10 | |10 | 5 | 12.2
|3 | 11 | |11 | 7 | 54.6
|3 | 12 | |12 | 8 | 74.6
|3 | 13 | |13 | 9 | 96.3
But.. it would have been "so easy" to just add a column to the join table of the first case... But then the "weight" data would be floating in an unknown dimension as it wouldn't be associated to any Java class...
Do this makes sense? is there a best practice to do this with hibernate?