Nathan Feger
Nathan Feger

Reputation: 19496

How do I map a nested collection, Map<Key,List<Values>>, with hibernate JPA annotations?

I have a class I am not sure how to annotate properly.

My goal for Holder::data:

I am also open to a different design that removes the map, if that would make for a cleaner design.

@Entity
public class Holder extends DomainObject {
  private Map<Enum,List<Element>> data;
}

@Entity
public class Element extends DomainObject {
  private long valueId;
  private int otherData;
}

@Mappedsuperclass
public class DomainObject {
 // provides id
 // optimistic locking
 // create and update date
}

Upvotes: 15

Views: 15055

Answers (3)

Anton
Anton

Reputation: 106

Here is a blog about collection of collections in hibernate https://xebia.com/blog/mapping-multimaps-with-hibernate/

Hope it will help. It helped me.

Regards, Anton

Upvotes: 3

Maarten Winkels
Maarten Winkels

Reputation: 2417

I don't think it is possible with hibernate(-core) to map any collection of collections:

Collections may contain almost any other Hibernate type, including all basic types, custom types, components, and of course, references to other entities.

(from the official doc)

Notice the almost and the omission of the collection type.

A workaround: You need to introduce a new type 'in between' the collection holder and the element. This type you can map as an entity or a component and it refers the original content of the map, in this case a list.

Something like:

@Entity
public class Holder extends DomainObject {
  @OneToMany
  private Map<Enum,InBetween> inBetweens;
}

@Entity
public class InBetween extends DomainObject {
  @OneToMany
  private List<Element> elements;
}

@Entity
public class Element extends DomainObject {
  private long valueId;
  private int otherData;
}

@Mappedsuperclass
public class DomainObject {
 // provides id
 // optimistic locking
 // create and update date
}

The rest of the mapping depends on your particular situation, but is rather straightforward.

Upvotes: 10

ngeek
ngeek

Reputation: 7883

Please note that the referred link to the Hibernate documentation seems out of date, I found the following working: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/collections.html

Upvotes: -1

Related Questions