How best to use hibernate in a simple scenario (questions at end of the post)
Lets say I have this Data Model in code:
class UserGroup
{
int id;
String name;
}
class User
{
int id;
String userName;
}
For the User and UserGroup classes, the underyling database table will look exactly as defined by the classes above.
Now, a User can belong to one or more UserGroups.
In a database table called USERGROUPMAP, this can be represented as:
USERID INT
USERGROUPID INT
In code, how will I represent that relation? The options I can think of are:
Option 1: (The UserGroup class contains a collection of the users belonging to it)
class UserGroup
{
int id;
String name;
UserCollection usersThatBelongInThisGroup;
}
Option 2: (The User class contains a collection of groups it belongs to)
class User
{
int id;
String name;
UserGroupCollection groupsThatIBelongTo;
}
Option 3: (A class that represnts a database table called USERGROUPMAP. In order to find out if a user belongs to a group etc, this class will need to be checked in-code)
class UserGroupMap //Class that represents the USERGROUPMAP table.
{
int userId;
int userGroupId;
}
The questions:
(A) If I use the 3rd option, then where is the benefit of using hibernate (after all its just another class representing a table)? I mean, I should be able to define a collection in class Users or UserGroup, and hibernate should take care of the insert/updates in USERGROUPMAP for me. So I think that rules out Option 3.
(B) If I use the 1st option, then whats the point of holding information about groups in the 2nd option? (since it can become redundant)
(C) Similarly, if I use the 2nd option then whats the point of the collection of users in the 1st option?
How is this to be tackled in a ORM like hibernate?