2

I'm trying to map my Hashmap in Hibernate. All examples I can find are simply like this:

class FooBar{
    Map<String,String> myStrings;
}

Which would simply map to

<map role="ages">
<key column="id"/>
<index column="name" type="string"/> 
<element column="age" type="string"/> 
</map>

However, I use a more object-oriented approach in my Java code. Kind of like the following:

class Bar{
    private Map<String, Foo> myFoos;
}

How would I go about mapping this? As the relationshop? Of otherwise defined: How can I map a one-to-many in a Map?

Thanks, Bart

2
  • many-to-many with a Map is contradictory. A Map maps a key to exactly one element. So it's one-to-many. Apart from that: I don't know any Hibernate specifics but JPA has @MapKey. Commented Aug 6, 2010 at 11:43
  • Oops, I meant one-to-many. I edited it in original post. Thanks for the remark Commented Aug 6, 2010 at 11:58

1 Answer 1

2

There are a few examples in the Hibernate reference manual chapter on Collection Mapping. You would want to do something like

<map name="foos">
    <key column="id"/>
    <index column="name" type="string"/> 
    <one-to-many class="Foo"/>
</map>

The difference is <one-to-many class="Foo"/> - this will map the relationship by using a foreign key column to the ID of the Foo table in the parent table (i.e. the object that has the Map of foos).

There are several more flavors and variations of how you can map this based on exactly the type of relationship you want, see the manual for more examples.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.