1


I am working on a Java project on my spare time,
I started using JPA 2.1 and learning to use annotations.
I have a class named Schedule that I want to contain this field:

private HashMap<LocalDate, ArrayList<Lesson>> theLessons

Lesson is another entity in my Database, LocalDate is the Java class.
Is that possible?

I tried to do it combining @OneToMany with @MapKey like in How do you map a "Map" in hibernate using annotations? but with no effect.
I am thinking that maybe I will need to create other Entities to facilitate this, like maybe a ListOfLessons, that will contain the ArrayList<Lesson> in order to shorten the HashMap to :

private HashMap<LocalDate, ListOfLessons>

Any help welcome

Community
  • 1
  • 1
Dimitris
  • 3,975
  • 5
  • 25
  • 27
  • how do you expect this to be stored in the database? what tables, columns? – Neil Stockton Jun 14 '14 at 07:49
  • @Neil Stockton : Well that is the issue, I don't have much experience with designing DBs. I don't mind how it is saved, I just want to have this information – Dimitris Jun 14 '14 at 11:29
  • You need to understand and draw out the relation between what a localDate, schedule and Lesson are. Why would a particular localDate have a list of lessons associated to it, and what is a localDate exactly? ListofLessons would have the LocalDate and a 1:m list of Lessons – Chris Jun 14 '14 at 17:02

2 Answers2

1

Just create an intermediate "Entity" and have a Map (as you presumed) and you'll find that in any decent JPA docs.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
1

What I did that appears to be working fine:

@Entity
public class Schedule implements Serializable {
....
    @OneToMany
    @MapKey(name = "theDate")
    private Map<LocalDate, ListOfLessons> allLessons = new HashMap<>();
....
}
@Entity
public class ListOfLessons implements Serializable {
...
    private LocalDate theDate;
    @OneToMany
    private List<Lesson> allLessons = new ArrayList<>();
...
}

Notice that ListOfLessons' field called theDate is used as a Map Key in class Schedule

Dimitris
  • 3,975
  • 5
  • 25
  • 27