1

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?

1 Answer 1

1

By using @MapKey you inform JPA that instead of having simple collection (like list or set of person), you want the relationship represented as map for which the key is one of the entities properties, the one which you include in your MapKey annotations.

You annotated the relationship with MapKey(name) and JPA holds the persons under their names values. You added person a and b, so the keys are a, b. The x, y keys that you entered are lost once you save the Foo to the DB. There is no extra column in DB to store those values, only the Person name is stored. Upon the Foo entity retrievals, all the Person entities are fetched and then placed into the map using their names fields as the keys, so your x,y values are replaced by the actual names values.

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.