Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes JPA Certification (OCEJPA) and the fly likes How to use Map<,> collection in OneToMany Relationship between entities in JPA 2 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » JPA Certification (OCEJPA)
Bookmark "How to use Map<,> collection in OneToMany Relationship between entities in JPA 2" Watch "How to use Map<,> collection in OneToMany Relationship between entities in JPA 2" New topic
Author

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

Singh Harmeet
Ranch Hand

Joined: Aug 05, 2011
Posts: 115

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.


With Regards :-
Harmeet Singh
Florin Vasile
Greenhorn

Joined: Feb 14, 2013
Posts: 8
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.


FVasi
OCPJP 6, OCEJPAD 6
Sathi Krishna
Ranch Hand

Joined: Oct 21, 2007
Posts: 51

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

Joined: Jun 01, 2010
Posts: 14
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.

OCPJP, OCEJWCD, OCEJPAD, OCEEJBD
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to use Map<,> collection in OneToMany Relationship between entities in JPA 2
 
Similar Threads
JPA: multiple many-to-many realationships between same two tables?
Problems in JPA with a Collection of Dates
The "optional" element on @OneToMany and @ManyToMany
Mysql auto generated PK used for another table and JPA
Best practice of mapping collection of enum