I am quite new to Hibernate so I am not entirely sure if what I want to do is even possible (or the right thing to do) so if it is not, feel free to suggest other ways of achieving what I am looking for.
I have 2 entities, Competition and Fixture. There is a One-to-Many relationship between them. I know how to set up the annotations to achieve this, but what I am struggling with is making the relationship bidirectional. If my application were to run for a long time, the number of Fixtures belonging to a competition would build up. The most common way I will be accessing the Fixture objects is via a Competition by specifying a particular date (e.g. getFixtures(today)). I thought I could implement this by having a Map in the Competition class that maps the date of the Fixture to a collection of Fixtures for that date. I have no idea how to set this up in Hibernate though.
Here is a simplified set of POJOs and Annotations that illustrate what I have so far:
@Entity
public class Competition {
// This is what I would like to have.
private Map<Date, Collection<Fixture>> fixtureMap;
public Collection<Fixture> getFixtures(Date day) {
return fixtureMap.get(day);
}
// This is all I know how to do.
private Collection<Fixture> fixtureList;
@OneToMany(mappedBy = "competition")
public Collection<Fixture> getFixtureList() {
return fixtureList;
}
}
@Entity
public class Fixture {
private Competition competition;
@ManyToOne
public Competition getCompetition() {
return competition;
}
}
As you can see from this I can set the relationship up to access the entire set of Fixtures for a competition. But to get the Fixtures for a specific day I would have to iterate over the entire collection of Fixtures and check the dates of each. Is there any way I can get Hibernate to handle the mapping from Date to a Collection of Fixtures? If I could do that then I would be able to simply access the collection of Fixtures for that day using the Date as the key in the Map.
No direct annotation can help. You will have to write a query for fetching fixtures of particular date.