Question

I've used XML and hierarchical databases for a long time, where ownership is easy to determine. Now I'm trying out a relational database model in which I have a runtime context I'm loading entities to with unique ids and relational properties such as ProductId etc.

My question is how I go about to add some kind of ownership to this model? If I want to define a relationship where the target-entity is the owning parent of the entity. How can I define this difference to a reference relation and persist this in a SQL-database with minimal extra information? Is there any support in SQL (MS) to define the type of relationship?

In the end, what I want is to be able to figure out what other entities to delete when some other entity is deleted (all owned entities). Also when serializing this entity to XML I want to serialize the referenced entities as normal id-elements and the owned entities with full XML.

<Notebook Id="1">
  <LibraryId>5</LibraryId> <!-- Referenced entity -->
  <AuthorId>6</AuthorId> <!-- Referenced entity -->
  <Notes> <!-- Owned entities -->
    <Note Id="2" />
    <Note Id="3" />
    <Note Id="4" />
  </Notes>
</Notebook>

The Note-entity is normally stored separated from Notebook in its own SQL-table with a NotebookId-column. But how do I define this column as a owned relationship? I guess I could call it OwnerId or OwningNotebookId and just analyze the name of the column. But I was hoping for a better method. What do you suggest?

Was it helpful?

Solution

The main difference is that the reference is held on the Many side of the One-to-Many link.

For Library and Author, the reference is on the Notebook table, as each Library and Author can have many notes books.

For the Notes, the reference is on the Note table for the same reason.

The sample schema below shows the links.

CREATE TABLE Author
(
    id int primary key,
    name varchar(100)
);

CREATE TABLE Library
(
    id int primary key,
    name varchar(100)
);

CREATE TABLE Notebook
(
    id int primary key,
    libraryid int not null references Library(id),
    authorid int not null references Author(id)
);

CREATE TABLE Note
(
    id int primary key,
    notebookId int not null references Notebook(id)
                               on delete cascade,
    note  varchar(100)
);

The link between Note and Notebook has got an "on delete cascade" option, which means that if the Notebook is deleted, the Note is deleted as well automatically by the database.

The default option "on delete restrict" will prevent a parent row from being deleted while a child row exists.

Making the NotebookId not null means that a note can't be created without a corresponding notebook so a notes lifecycle is always linked to the parent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top