I have been following the CaveatEmp example application and am trying to understand something. The association between Category and Item is mapped as two one-to-many associations to a CategorizedItem association class rather than one many-to-many association between Item and Category. I think I understand this in principle. Just as in this example I have a need for a many-to-many type relationship, but want it to be bi-directional. However looking at the test cases it appears that if you use this type of mapping you must save both the Item and Category before you can persist the CategorizedItem. Here is the code from the example:
Code:
itemDAO.makePersistent(auctionOne);
new CategorizedItem(u1.getUsername(), carsLuxury, auctionOne);
Is there a way to configure things so that you don't have to do this. For instance, is there a way to make the following work:
Code:
CategorizedItem catItem=new CategorizedItem(u1.getUsername(), carsLuxury, auctionOne);
itemDAO.makePersistent(auctionOne);
OR EVEN BETTER:
Code:
auctionOne.addCategory(new Category(...));
itemDAO.makePersistent(auctionOne);
Hibernate version: 3.0
Mapping documents:CategorizedItemMapping:
Code:
<many-to-one name="category"
insert="false"
update="false"
not-null="true"
access="org.hibernate.auction.persistence.DirectSetAccessor"
column="CATEGORY_ID"/>
<many-to-one name="item"
insert="false"
update="false"
not-null="true"
access="org.hibernate.auction.persistence.DirectSetAccessor"
column="ITEM_ID"/>
Item Mapping
Code:
<set name="categorizedItems"
cascade="all-delete-orphan"
inverse="true"
lazy="true"
access="org.hibernate.auction.persistence.DirectSetAccessor">
<key foreign-key="FK2_CATEGORIZED_ITEM_ID">
<column name="ITEM_ID" not-null="true" length="16"/>
</key>
<one-to-many class="CategorizedItem"/>
</set>
Category Mapping
Code:
<set name="categorizedItems"
cascade="all-delete-orphan"
inverse="true"
outer-join="false"
access="org.hibernate.auction.persistence.DirectSetAccessor">
<key foreign-key="FK1_CATEGORIZED_ITEM_ID">
<column name="CATEGORY_ID" not-null="true" length="16"/>
</key>
<one-to-many class="CategorizedItem"/>
</set>