views:

51

answers:

1

This is a real beginner Hibernate problem. I have a problem with the mappings for two tables. The first table is MARKET, and the second is MARKET_MENU_BRANCH which contains a list of rows for each MARKET row. When I save a new Market, I want it to insert both MARKET and MARKET_MENU_BRANCH rows, but in fact it seems to insert MARKET and then attempt an update on MARKET_MENU_BRANCH rows, which don't exist, causing an error. What I am doing wrong? My tables look like this:

mysql> describe MARKET;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   | PRI | NULL    |       | 
| name  | varchar(100) | YES  |     | NULL    |       | 
+-------+--------------+------+-----+---------+-------+

mysql> describe MARKET_MENU_BRANCH;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| marketId | int(11)      | NO   | PRI | 0       |       | 
| sequence | int(11)      | NO   | PRI | 0       |       | 
| name     | varchar(100) | YES  |     | NULL    |       | 
+----------+--------------+------+-----+---------+-------+

My domain objects look like:

public class Market implements Serializable {
    private int id;
    private String name;
    private List<MarketMenuBranch> marketMenuBranches;
    // accessors / mutators etc...

public class MarketMenuBranch implements Serializable {
    private MarketMenuBranchId id;
    private String name;
    // accessors / mutators etc...

public class MarketMenuBranchId implements Serializable {
    private int marketId;
    private int sequence;
   // accessors / mutators etc...

and my mappings look like:

<class name="Market" table="MARKET">
    <id name="id"/>
    <property name="name"/>
    <list name="marketMenuBranches">
        <key column="marketId"/>
        <list-index column="sequence"/>
        <one-to-many class="MarketMenuBranch"/>
    </list>
</class>

and

<class name="MarketMenuBranch" table="MARKET_MENU_BRANCH">
    <composite-id name="id" class="MarketMenuBranchId">
        <key-property name="marketId"/>
        <key-property name="sequence"/>
    </composite-id>
    <property name="name"/>
</class>
+4  A: 

You have a parent/child relationship, you will find insights in this page of the doc.

Basically you need to save(...) the child or use the cascade attribute.

Guillaume