HectorLector
HectorLector

Reputation: 1911

Hibernate HashMap mapping

I am new to hibernate and I need to map an existing class structure to the database. Right now I have a Player, Arsenal and Weapon class. Every Player has his own (one) Arsenal - no problem. In the Arsenal there is a HashMap containing a weaponID and the amount of this weapon. For example (ID=10 is shotgun, there are 7 rounds of amo left). To make it more complicated I have more of this Maps with different styles of weapons:

@Entity
class Arsenal
{
   @Id
   @GeneratedValue
   int arsenalID;

   //weaponID - how many
   HashMap<Integer, Integer> explosiveWeapons;
   HashMap<Integer, Integer> rifleWeapons;
   HashMap<Integer, Integer> someOtherTypeOfWeapons;
}

How would I map something like that in hibernate 4 with Annotations?

And secondly: Is it better to have a table Arsenal:

arsenalID | weaponID | amount

Or better more tables like this:

arsenalID | explosiveWeaponID | rifleWeaponID | ...

and then for each weaponType one table with id/amount?

I would prefer not to change the classes/code to much/at all, but if there are better ways to archive this, I am grateful for suggestions.

Upvotes: 0

Views: 1326

Answers (1)

Matt Rick
Matt Rick

Reputation: 146

It looks like your Hashmaps contain entries that would best be mapped with the Hibernate annotation @ManyToMany as a @JoinTable.

Basically, what you want is a table like this:

CREATE TABLE arsenal_entry {
    ... --Id here, or you could use a synthetic key, but if you're new to hibernate I wouldn't recommend that.
    player_id integer references player,
    weapon_id integer references weapon, --If weapons aren't defined in an enum, otherwise this should be a varchar / text
    count integer
}

There's a pretty good description of many-to-many here with good examples.

Upvotes: 1

Related Questions