1

I am trying to create a sample Report card application and want to persist a map between subject and student's grade This is my scorecard class:

@Entity
public class ScoreCard {
    @NotNull @ElementCollection @ManyToMany(cascade=CascadeType.ALL)
    private Map<Subject, String> gradesForMainSubject = new HashMap<Subject, String>();
}

But when trying to save data I always end up with

Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: gradesForMainSubject

Subject itself is a Managed entity (annotated by @Entity). Any suggestions on how can I move forward.

Suryavanshi
  • 595
  • 1
  • 7
  • 24
  • You have to use `@MapKeyColumn', checkout this thread [http://stackoverflow.com/questions/7525320/how-to-add-a-hashmapstring-object-in-an-entity-class](http://stackoverflow.com/questions/7525320/how-to-add-a-hashmapstring-object-in-an-entity-class) – Uppicharla Oct 19 '15 at 03:06
  • Wrong, @MapKeyColumn need not be specified. It defaults to attribute name + "KEY". So in his case, this will default to GRADESFORMAINSUBJECT_KEY. – Ish Oct 19 '15 at 03:19

1 Answers1

3

You cannot use both @ElementCollection and @ManyToMany at the same time for a collection field.

If the values of your collection are entities, then you can use either one of the 2: @OneToMany or @ManyToMany

If the values of your collection are non-entities, then you must use @ElementCollection.

In your case, the values of your map are String which are not entities. Therefore you need to use @ElementCollection. Remove the @ManyToMany mapping. This rule should be followed, regardless of whether you map key is an entity or not.

Ish
  • 3,992
  • 1
  • 17
  • 23
  • Is there any way to cascade the save operations. I get error if I don't save `Subject` before saving `ScoreCard` – Suryavanshi Oct 19 '15 at 03:35
  • 1
    Cascade applies only to entity relationship mappings (not for element collections) and only applies to the values of your map collection, but not the key. Therefore there is no other way, but you must have a pre-existing Subject entity, or persist first the Subject entity before saving Scorecard. – Ish Oct 19 '15 at 03:40