Relationships and Cardinality

source :Agile Java Development with Spring, Hibernate and Eclipse by Anil Hemrajani

Database relationships aretypically defined in terms of direction and cardinality (multi-plicity in OO terminology).From an OO perspective,relationships are defined as associ-ation,inheritance,or aggregation.Many software development projects use ORM eitherwith existing databases or are required to conform to standards established by a databasegroup within the organization;hence,I will approach our relations discussion from adatabase perspective.

Unidirectionalis when one table knows of another,but not vice versa.For example,you might have a record that uses a unique primary key;this same primary key can beused as a foreign key by records in a child table,thereby establishing a unidirectionalrelationship.In a bidirectionalrelationship,records in both tables would know about eachother.For example,assume we have two tables named Employeeand Projectto storeinformation about which employees worked on which project.In the Projectrecord,wemight have an EmployeeIdforeign key.On the flip side,we might have a ProjectIdkeyin the Employee table.Cardinality can be defined as one-to-one,one-to-many (or many-to-one depending onwhich direction you look at the relationship),and many-to-many.We look at each briefly:

  • A one-to-one relationshipis when a record in table 1 can have exactly one associ-ated record in table 2.For example,a record in a Person table might have exactlyone related record in a JobTitletable.
  • A one-to-many relationshipis typically seen in parent-child relationships where aparent record can have several related records in a child table (for example,relatedvia the parent’s primary key).
  • A many-to-many relationshipis where a record in table 1can have several relatedrecords in table 2 and vice versa.For example,an Employeetable might have morethan one record in a Projecttable (because an employee can be involved in multi-ple projects).On the flip side,a record in the Projecttable might have severalrelated records in the Employeetable because a project can have multipleemployees assigned to it.Also,this type of relationship is typically achieved byusing an (extra) association table (for example,a ProjectEmployee table that con-tains foreign keys pointing to the two main tables).

Leave a comment

Filed under OOAD

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s