1


我在Java业余时间从事一个项目,
我开始使用JPA 2.1并学习使用annotations.
我有一个名为Schedule我想包含此字段的类:

private HashMap<LocalDate, ArrayList<Lesson>> theLessons

课程是我的数据库中的另一个实体,LocalDate 是 Java 类。
那可能吗?

我尝试将@OneToMany 与@MapKey 结合起来,就像在How do you map a "Map" in hibernate using annotations? 但没有效果。
我在想,也许我需要创建其他Entities来促进这一点,比如 a ListOfLessons,它将包含ArrayList<Lesson>以缩短HashMapto :

private HashMap<LocalDate, ListOfLessons>

欢迎任何帮助

4

2 回答 2

1

只需创建一个中间“实体”并拥有一个 Map(如您所料),您会在任何体面的 JPA 文档中找到它。

于 2014-06-14T12:48:17.990 回答
1

我所做的似乎工作正常:

@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<>();
...
}

请注意,ListOfLessons' 字段theDate被用作类中的 Map KeySchedule

于 2014-06-15T07:29:46.427 回答