Hi,
I'm not sure if this has been discussed before, couldn't find anything in the search (well, I could find a lot, but nothing matching exactly...).
I'm looking at how I can manage a many-to-many relationship in a less complex way than I'm currently doing.
I've got a spring/hibernate small app to manage two simple entities, User and Subscription.
The way I've got this currently modeled is with a collection of subscriptions on the User object:
Code:
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(
name="USER_SUBS",
joinColumns = @JoinColumn(name="USER_ID"),
inverseJoinColumns = @JoinColumn(name="SUBSCRIPTION_ID")
)
public Collection<Subscription> getUserSubscriptions() {
...
}
At the service level, I have methods to add/remove a subscription from a user. The front end is passing only the subscription ID, so my steps are at the moment:
1. Fetch the Subscription object using a subscriptionService
2. In my userDAO, call:
Code:
public void addSubscription(User user, Subscription sub) {
user.getSubscriptions().add(sub);
getHibernateTemplate().saveOrUpdate(user);
}
And something similar to remove.
Now, I'm wondering if there's something else I could do, since this seems to be doing a lot of stuff just to do the equivalent of a "DELETE FROM USER_SUBS WHERE USER_ID = ? AND SUB_ID = ?"
* I have to load up the proper Subscription object since I have only the ID
* I resave the whole user just to persist the change to their subs collection
What trick am I missing? How can I manager that link table to add/remove those links in a lighter manner? Anything I could call on getHibernateTemplate() in the DAO?
Am I wrong in thinking there is an overhead? Is second level caching allowing these steps to be just as fast as something more "targeted"?