title: Cascade delete and one-to-one mapping in hibernate
body: <p>In a web application which creates Bill for SaleOrder for a Buyer, I tried to create database tables and hibernate mappings. The relationships between the entities are:</p>
  <blockquote>
  <ol>
  <li><p>A Bill has a Buyer and a SaleOrder</p>
  </li>
  <li><p>A SaleOrder has a Buyer.</p>
  </li>
  <li><p>When a SaleOrder is deleted, the associated Bill must be deleted.</p>
  </li>
  </ol>
  </blockquote>
  <p>I Implemented the java classes,created tables.</p>
  <p>In the schema, table  SALEORDER has a FK column 'BUYER_ID'.
  This table has no other foreign key columns.
  The table BILL has two foreign keys, BUYER_ID and SALEORDER_ID.</p>
  <p>How do I map Bill and SaleOrder using <em>one-to-one relation</em> <strong>AND</strong> make sure that when a SaleOrder is deleted, the Bill is also deleted?</p>
  <p>I am confused because, <em>since the SaleOrder table has no foreign key</em> named INVOICE_ID, how can I map the following in SaleOrder.hbm.xml?</p>
  <pre><code>&lt;!-- 1-to-1 modelled using n-to-n + unique  --&gt;
      &lt;many-to-one name=&quot;invoice&quot; class=&quot;Invoice&quot; column=&quot;INVOICE_ID&quot; cascade=&quot;delete&quot; unique=&quot;true&quot;&gt;
      &lt;/many-to-one&gt;
  </code></pre>
  <p>If I put the mapping only in Bill.hbm.xml,will I be able to mention <em>cascade delete</em> (which should delete Bill when SaleOrder is deleted)?</p>
  <p>Hope someone can suggest a solution.</p>
  <hr />
  <p>The classes in my application are:</p>
  <pre><code>class Buyer{
     private Long buyerId;
     private String name;
  ...
  }
  
  class SaleOrder{
      private Long saleOrderId;
      ...
      private Buyer buyer;
  ...
  }
  
  class Bill{
     private Long billId;
     ...
     private Buyer buyer;
     private SaleOrder saleOrder;
  ...
  }
  </code></pre>
  <p>The schema is:</p>
  <pre><code>CREATE TABLE BUYER(
     BUYER_ID BIGINT NOT NULL PRIMARY KEY IDENTITY,
     NAME VARCHAR(100)
  );
  
  CREATE TABLE SALEORDER(
     SALEORDER_ID BIGINT NOT NULL PRIMARY KEY IDENTITY,
     BUYER_ID BIGINT NOT NULL,
  );
  
  CREATE TABLE BILL(
    BILL_ID BIGINT NOT NULL PRIMARY KEY IDENTITY,
    BUYER_ID BIGINT NOT NULL,
    SALEORDER_ID BIGINT NOT NULL,
  );
  ALTER TABLE SALEORDER ADD CONSTRAINT FK_SO_BUYER FOREIGN KEY(BUYER_ID) REFERENCES BUYER(BUYER_ID);
  ALTER TABLE BILL ADD CONSTRAINT FK_BILL_BUYER FOREIGN KEY(BUYER_ID) REFERENCES BUYER(BUYER_ID);
  ALTER TABLE BILL ADD CONSTRAINT FK_BILL_SO FOREIGN KEY(SALEORDER_ID) REFERENCES SALEORDER(SALEORDER_ID);
  </code></pre>