3

I'm looking how to map in JPA a hashmap with its value being a list.

I've 2 entities:

EntityA {
  @Id
  @GeneratedValue
  private Integer id;

  @MapKey(name = "nature")
  @MapKeyEnumerated(EnumType.STRING)
  @OneToMany(mappedBy = "entityA", cascade = CascadeType.ALL)
  private Map<NatureEnum, List<EntityB>> mapEntityB = new HashMap<NatureEnum, List<EntityB>>();     
}


EntityB {
  @Id
  @GeneratedValue
  private Integer id;

  @ManyToOne
  @JoinColumn(name = "ID_ENTITYA", nullable = false)
  private EntityA entityA;

  @Column(name = "NATURE", nullable = false)
  @Enumerated(EnumType.STRING)
  private NatureEnum nature;
}

You will have guessed that of course the map doesn't work as it's missing something telling it it's not just one EntityB in it.

The rest does work and if i change the map by a regular List it works fine. So how can i manage to "group by" my EntityB in one list depending on the value of Nature?

Thanks in advance for your help.

TheBakker
  • 2,852
  • 2
  • 28
  • 49
  • Found this http://stackoverflow.com/questions/939235/how-do-i-map-a-nested-collection-mapkey-listvalues-with-hibernate-jpa-anno so it seems it's not possible without creating a entity in between ... – TheBakker Apr 01 '14 at 17:09
  • 4
    That's right, JPA does not support nested collections. You need to change your model. See: http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Nested_Collections.2C_Maps_and_Matrices – gadget Apr 01 '14 at 17:25
  • Wrap `List` into a new entity in order to have `Map mapEntityW`, and put your list into `EntityW`. **EDIT**: @gadget's comment shows you exactly how to do this. – VH-NZZ Apr 01 '14 at 17:30
  • Thanks guys. Wonder if there is anyway to mark this as solved when the answers are in comments? Regards. – TheBakker Apr 02 '14 at 13:31
  • Thank you for the Wiki @gadget! And about other guys, thank you as well! Hope you have a great coding time! – Nikolas Freitas Mr Nik May 02 '22 at 00:37
  • @TheBakker - Which of the comment did really Help you? I am trying to have `Map` in my Entity. or even `Map` can be also fine if possible? – GreenROBO Sep 28 '22 at 06:10

0 Answers0