I've been struggling for a while now to solve the problem of persisting a Hashmap within an object ie.:
private Map<String, String> myMap;
private Map<String, Pet> petMap;
I've found most documentation to be misleading. For example at
http://www.hibernate.org/hib_docs/annot ... ollections:
@Entity
public class Software {
@OneToMany(mappedBy="software")
@MapKey(name="codeName")
public Map<String, Version> getVersions() {
return versions;
}
...
}
This is the wrong MapKey and causes errors for me. The only way i got it to work was to use the new MapKey i.e.
import org.hibernate.annotations.MapKey; //IMPORTANT!!
...
@CollectionOfElements
@MapKey(columns={
@Column(name="`key`")
})
private Map<String, String> myMap;
This solves the MySql problem where the key is a reserved word - additionally you can call the key column whatever you wish.
Now, for private
Map<String, Pet> petMap; i have:
@OneToMany(cascade = CascadeType.ALL)
@MapKey(columns={
@Column(name="`key`")
})
@JoinColumn(name="petMapOwner_id")
private Map<String, Pet> petMap;
This works fine. What hibernate will do is add a column to the pet table called "key". This will hold the String representation of the key that points to the pet object in question. However, this doesn't quite imitate true hashmap behaviour. For example, suppose you had:
petMap.put("pet2", pet2);
petMap.put("pet3", pet3);
// Hibernate doesn't do this properly - it only stores
// one row Per String and Pet (Object) Pairings
petMap.put("pet3again", pet3);
All the rows in the DB tell you is that pet2 is indexed by the string "pet2" and pet3 is indexed by the string "pet3". But somehow there should be another indication that pet3 is indexed by the string "pet3again" aswell.
"who cares?" i hear you cry. Well... ok its only a problem if you actually want to point to the same object twice with 2 different string hash indexes. And you could just clone the object if you wanted this. But anyway, thought i'd post this and see if
a) people think i'm doing this right in the first place
b) anyone would ever want to index the same object twice by different string indexes
c) if there is sufficient people agreeing with a) and b), then its a bug that needs looking into/process that needs refining.
Thanks
Dan