This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Sorry for the long post as I try to describe the problem context in details.
My problem is to map a relationship table with both regular and composite foreign keys in it.
Assume we have three tables:
user(first_name, last_name, birth_day, gender). The PK is composite of first_name and last_name two columns
has_friend(social_site_id, user_first_name, user_last_name, friend_first_name, friend_last_name). The PK is the whole table
Here, the has_friend table defines relationship beteen users for a given social site which basically has three foreign keys:
FK1. social_site_id refers to social_site(id)
FK2/CompositeKey (user_first_name, user_last_name) refers to user(first_name, last_name)
FK3/CompositeKey (friend_first_name, friend_last_name) refers to user(first_name, last_name)
This is the mapping file
<class name="HasFriend" table="has_friend">
<key-many-to-one name="socialSite" class="SocialSite" column="social_site_id"/>
In the simple load() call below in which I did not see any SQL generated(show_sql logging is turned on) and the result var "expected" only contains the query instance's id.
So anything wrong with my mapping here? Notice there are two level composite-id here: one at HasFriend class and one at User class.
(i) The load() did not generate any sql, but getHibernateTemplate().saveOrUpdate(queryInstance) actually generates a proper SELECT statement to check if the row already exists in the table, but it did not generate an insert statement. This test indicates that Hibernate reads the mapping file, but did not always execute it, nor reporting any mapping error.
(ii) I have equals and hashCode and Serializable implemented for HasFriend class.
(iii) For User class mapping(source code not shown here), I used a UserID class to define the composite-id with both firstName and lastName and load() call works fine for a given first and last name.
Thanks for the help
// Construct the query instance
SocialSite queryPara1 = new SocialSite();
User queryPara2 = new user();
User queryPara3 = new user();
HasFriend queryInstance = new HasFriend();
// fetch the object from has_friend table
HasFriend expected = getHibernateTemplate().load(HasFriend.class, queryInstance);