Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to use Map<,> collection in OneToMany Relationship between entities in JPA 2

 
Singh Harmeet
Ranch Hand
Posts: 115
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i prepare my self of OCE-JPA certification , in PRO JPA 2 book chapter 5 , explain the Map<> use in OneToMany relationship between Entities . when i try to insert the element in Map<String ,String> there is fowling exception throw. . please explain the exception and explain how to use Map<> in relationship , with small example.
 
Florin Vasile
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

you would use OneToMany if you would have a relationship between 2 entities. In this case you have an ElementCollection of String.

You should have Map<String, Entity> if you have a key as a string and a relationship.
 
Sathi Krishna
Ranch Hand
Posts: 51
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should have to use @ElementCollection for Map<String,String>.
If the Map value is Entity, then use @OneToMany or @ManyToMany.
If the Map value is basic type or Embedded type, then use @ElementCollection.

Thank You
SVKrishnaReddy
 
Bobby Jakachira
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest way of thinking about this for anyone who would want to know is take

Map<key,Value>

Forget about Key type.. The value part is the important part for mapping the relationships.

You only put relationship annotations to real entities. thus the value part should be an Entity and nothing else for this to be marked @OneToMany etc.

Anything else as a Value part, such as embeddables and basic types should be mapped as @ElementCollection.

For the exam, mapping keys to the database is important and tricky. I got 11% less because of that section.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic