I am trying to understand the usage of Map in hibernate by writing a sample program, but I am not getting the use of the Map. Here is what I am trying to do:
Foo.java
@Entity
public class Foo {
@Id
@GeneratedValue
private int id;
@OneToMany(cascade = CascadeType.ALL)
@MapKey(name = "name")
private Map<String, Person> persons = new HashMap<String, Person>();
// Setter & Getters
}
Person.java
@Entity
public class Person {
@Id
@GeneratedValue
private int id;
private String name;
// Setters & Getters
}
Now here is my sample program:
public static void main(String[] args) {
session.beginTransaction();
Foo f = new Foo();
Person p1 = new Person("a");
Person p2 = new Person("b");
Map<String, Person> persons = new HashMap<String, Person>();
persons.put("x", p1);
persons.put("y", p2);
f.setPersons(persons);
int id = (Integer) session.save(f);
session.getTransaction().commit();
listFoo(id);
}
private static void listFoo(Integer id) {
Session session = //get the session;
session.beginTransaction();
Foo foo = (Foo) session.get(Foo.class, id);
System.out.println("foo.getId()="+foo.getId());
Map<String,Person> persons = foo.getPersons();
for (String key : persons.keySet()) {
System.out.println("key="+key+" , value = "+persons.get(key).getName());
}
}
Here is the output:
foo.getId()=1
key=a , value = a
key=b , value = b
In this program, while saving the Foo object I have set the keys to x & y, these keys are not used while saving the entities for Foo & Person, so does it mean that the HashMap keys are ignored so I can give any value to it? Can you please clarify?