I am learning ORM using Hibernate by creating a movie rental application. Currently, I have the following three entities for persistence:
- User
- Movie
- Rental (composite element for many-to-many mapping between above two)
Now, to handle the cart updates, I have the following code in a session scoped bean:
@ManagedBean
@SessionScoped
public class UserManager extends BaseBean implements Serializable
{
....
private Map<Integer, Movie> cart;
....
public void updateCart(Movie selectedMovie)
{
if (!isLoggedIn()) {
return;
}
int id = selectedMovie.getMovieID();
if (cart.containsKey(id)) {
cart.remove(id);
}
else {
cart.put(id, selectedMovie);
}
}
}
Now for user's purchase scenario, I need to keep track of the number of rentals per movie. So, I thought of adding that property to the Rental
entity and use it as a value for the map. But, this class itself contains Movie
as a property for the mapping as below:
<set name="rentals" cascade="all" lazy="true" table="USER_MOVIES">
<key column="userRegistrationID" not-null="true"/>
<composite-element class="Rental">
<property name="bookingDate" column="bookingDate" type="date"/>
<many-to-one name="movie" column="bookedMovieID" class="Movie" not-null="true"/>
</composite-element>
</set>
So, while adding to / removing from cart, I will have to create / destroy an instance of the Rental
class, which would be a bad idea. So I am thinking that I should restructure my entities.
Am I right in assuming the above? Is there a better approach for the above?
I am using the following:
- JSF 2.1 + PrimeFaces
- Hibernate 4.3
- MySQL