Database Modeling and Design N. L. Sarda [email protected] (based on the text book and presentation on...
-
Upload
dorthy-sanders -
Category
Documents
-
view
216 -
download
1
Transcript of Database Modeling and Design N. L. Sarda [email protected] (based on the text book and presentation on...
Database Modeling and DesignDatabase Modeling and Design
N. L. [email protected]
(based on the text book and presentation
on UML by Niraj Trivedi)
2.2
Modeling and Database DesignModeling and Database Design
Entity Sets Relationship Sets Design Issues Mapping Constraints Keys E-R Diagram Extended E-R Features Introduction to UML Object Modeling in UML From ER to Relations
2.3
Why We ModelWhy We Model
We build models of complex systems because we cannot comprehend any such system in its entirety
Need to develop a common understanding of the problem and the solution
Cannot afford a trial-and-error approach
to communicate the desired structure and behavior of our systems
2.4
How We ModelHow We Model
The choice of which model we use has a profound influence on how a problem is attacked and how a solution is shaped
No single model is sufficient; every complex system is best approached through a set of independent models
The best models are connected to reality
2.5
DATA MODELDATA MODEL
represents operational data about real world events, entities, activities, etc.
model may be at various levels depending of requirements : logical or physical external, conceptual, internal
2.6
Data Model……Data Model……
a good model is easy to understand has a few concepts permits top-down specifications
model offers concepts, constructs and operations must capture meaning of data (data semantics)
which help us in interpreting the data
2.7
Data Model……Data Model……
semantics captured through data types, inter-relationships and data integrity constraints permitted values
uniqueness
existence dependence
restrictions on some operations such as insertions, deletions
2.8
ER MODEL….ER MODEL….
a few concepts
simple and easy-to-use
permits top-down approach for controlling details
useful as a tool for communication between designer and user during requirements analysis and conceptual design
2.9
ENTITYENTITY
an object that exists
distinguishable from other objects
could be concrete or abstract
Examples : this course on DBIS, Ganesh as a student, etc
2.10
ENTITY SET ENTITY SET
a set of similar entities need not be disjoint with other entity sets
e.g., supplier and customer may have common entities
example : set of all books in a library
entity set also called entity type or entity class
an entity is an occurrence or an instance of some entity type
2.11
ENTITY SET……ENTITY SET……
we often use the words ‘entity’ to mean ‘entity-set’
entity sets are named using singular common nouns :
Book
Student
Course
2.12
ATTRIBUTEATTRIBUTE
an entity has a set of attributes
attribute defines property of an entity entity Book has Price attribute
it is given a name
attribute has value for each entity
value may change over time
same set of attributes are defined for entities in an entity set
2.13
ATTRIBUTE….ATTRIBUTE….
Example : entity set BOOK has the following attributes
TITLE ISBN
ACC-NO AUTHOR
PUBLISHER YEAR
PRICE
a particular book has value for each of the above attributes
2.14
ATTRIBUTE….ATTRIBUTE….
an attribute may be multi-valued, i.e., it has more than one value for a given entity; e.g., a book may have many authors
an attribute which uniquely identifies entities of a set is called candidate key attribute of that entity set
composite attribute : date, address, etc
2.15
Composite AttributesComposite Attributes
2.16
PRIMARY KEYSPRIMARY KEYS
to distinguish occurrences of entities
distinction made using values of some attribute(s)
set of one/more attributes which, taken collectively, uniquely identify an entity in an entity set is called its candidate key Roll-number for a student
Acc-no for a book
2.17
EXAMPLE : A COLLEGEEXAMPLE : A COLLEGE
(some entities and their attributes)
STUDENT : rollno, name, hostel-no., date-of-birth
COURSE : courseno, name, credits
TEACHER : empno, name, rank, room-no, tel- phone
DEPT : name, tel-phone
Ex : identify primary keys of above entities.
2.18
EXAMPLE : A COLLEGE…EXAMPLE : A COLLEGE…
perception of reality and focus of design could have indicated more entities HOSTEL SEMESTER
Or, teacher could only be an attribute
EXERCISE : identify entities in a hospital and
give a few instances of each
2.19
RELATIONSHIPRELATIONSHIP
represents association among entities e.g., a particular book is a text for particular
course
the book ‘Database Systems’ by S. Sudarshan is text for course identified by code ‘CS644’
the student GANESH has enrolled for course CS644
2.20
RELATIONSHIP SETRELATIONSHIP SET
set of relationships of same type
words ‘relationship’ and ‘relationship set’ often used interchangeably
between certain entity sets binary relationship : between two entity sets
ternary relationship : among three entity sets
2.21
RELATIONSHIP SET….RELATIONSHIP SET….
binary relationship set STUDY between STUDENT and COURSE
relationship STUDY could be ternary among STUDENT, COURSE and TEACHER
What is the difference ?
a relationship may have attributes attribute GRADE and SEMESTER for STUDY
2.22
RELATIONSHIP SET….RELATIONSHIP SET….
relationships named using verbs or nouns
Study
Enroll
Order
2.23
DEPICTING A RELATIONSHIP DEPICTING A RELATIONSHIP
entity sets as a collection
entity instances by small circles
relationship instances by small rectangle with connections to involved entities
2.24
(Ram, Cobol)
(Sita, DBMS)
2.25
PRIMARY KEY FOR REPATIONSHIPSPRIMARY KEY FOR REPATIONSHIPS
made of primary keys of all participating entities e.g., primary key of STUDY is
(rollno, courseno)
2.26
RELATIONSHIP CARDINALITYRELATIONSHIP CARDINALITY
is a constraint on a relationship
it characterizes relationships further
given by indicating : how many entities of an entity set participate in a relationship
especially useful for binary relationships
Express the number of entities to which another entity can be associated via a relationship set.
2.27
RELATIONSHIP CARDINALITY…RELATIONSHIP CARDINALITY…
a relationship (set) R between entity (sets) A and B may be one of the following one-to-one : one entity in A is associated with at most
one entity in B
one-to-many : one entity in A may be associated with zero/more number of entities in B. However, one entity in B can be associated with at most one entity from A.
many-to-one : reverse of above definition (like a mathematical function)
many-to-many : one entity in A may be associated with any number of entities in B, and vice-versa.
2.28
RELATIONSHIP CARDINALITY…RELATIONSHIP CARDINALITY…
EXAMPLES : relationship TEACHES from TEACHER to COURSE is
one-to-many
(TAUGHT-BY from COURSE to TEACHER is many-to-one)
relationship STUDY between STUDENT and COURSE is many-to-many
2.29
E-R DiagramsE-R Diagrams
Rectangles represent entity sets.
Diamonds represent relationship sets.
Lines link attributes to entity sets and entity sets to relationship sets.
Ellipses/circles represent attributes
Double ellipses represent multivalued attributes.
Dashed ellipses denote derived attributes.
Underline indicates primary key attributes (will study later)
2.30
E-R Diagram With Composite, Multivalued, and E-R Diagram With Composite, Multivalued, and Derived AttributesDerived Attributes
2.31
Relationship Sets with AttributesRelationship Sets with Attributes
2.32
RolesRoles
Entity sets of a relationship need not be distinct
The labels “manager” and “worker” are called roles; they specify how employee entities interact via the works-for relationship set.
2.33
Roles …Roles …
Roles are indicated in E-R diagrams by labeling the lines that connect diamonds to rectangles.
Role labels are optional, and are used to clarify semantics of the relationship
2.34
Cardinality ConstraintsCardinality Constraints
We express cardinality constraints by drawing either a directed line (), signifying “one,” or an undirected line (—), signifying “many,” between the relationship set and the entity set.
E.g.: One-to-one relationship:
2.35
One-To-Many RelationshipOne-To-Many Relationship
In one-to-many relationship a loan is associated with at most one customer via borrower, a customer is associated with several (including 0) loans via borrower
2.36
Many-To-Many RelationshipMany-To-Many Relationship
A customer is associated with several (possibly 0) loans via borrower
A loan is associated with several (possibly 0) customers via borrower
2.37
Participation of an Entity Set in a Participation of an Entity Set in a Relationship SetRelationship Set
Total participation (indicated by double line): every entity in the entity set participates in at least one relationship in the relationship set
E.g. participation of loan in borrower is total
every loan must have a customer associated to it via borrower
2.38
Participation …Participation …
Partial participation: some entities may not participate in any relationship in the relationship set
E.g. participation of customer in borrower is partial
2.39
Alternative Notation for Cardinality Alternative Notation for Cardinality LimitsLimits
Cardinality limits can also express participation constraints
2.40
2.41
2.42
• Describe the real-world mapped above in words.• Can you represents this : a supplier may supply same part many times
. Relationship ‘supplies’ could also be ternary (by involving warehouse)
2.43
TERNARY RELATIONSHIPS TERNARY RELATIONSHIPS
be sure that your model reflects real-world correctly
ternary (or, of higher order) relationships are harder to understand
ternary relationship is not same as two binary relationships
2.44
2.45
2.46
E-RE-R Diagram with a Ternary Relationship Diagram with a Ternary Relationship
2.47
Cardinality Constraints on Ternary Cardinality Constraints on Ternary RelationshipRelationship
We allow at most one arrow out of a ternary (or greater degree) relationship to indicate a cardinality constraint
E.g. an arrow from works-on to job indicates each employee works on at most one job at any branch.
2.48
Ternary …Ternary …
If there is more than one arrow, there are two ways of defining the meaning. E.g a ternary relationship R between A, B and C with
arrows to B and C could mean
1. each A entity is associated with a unique entity from B and C or
2. each pair of entities from (A, B) is associated with a unique C entity, and each pair (A, C) is associated with a unique B
To avoid confusion we outlaw more than one arrow
2.49
Converting Non-Binary Relationships to Converting Non-Binary Relationships to Binary FormBinary Form
In general, any non-binary relationship can be represented using binary relationships by creating an artificial entity set. Replace R between entity sets A, B and C by an entity set E,
and three relationship sets as shown
Create a special identifying attribute for E
Add any attributes of R to E
2.50
Converting Non-Binary Relationships Converting Non-Binary Relationships (Cont.)(Cont.)
Also need to translate constraints Translating all constraints may not be possible There may be instances in the translated schema that
cannot correspond to any instance of R
Exercise: add constraints to the relationships RA, RB and RC to ensure that a newly created entity corresponds to exactly one entity in each of entity sets A, B and C
We can avoid creating an identifying attribute by making E a weak entity set (described shortly) identified by the three relationship sets
2.51
Existence DependenciesExistence Dependencies
If the existence of entity x depends on the existence of entity y, then x is said to be existence dependent on y. y is a dominant entity (in example below, loan) x is a subordinate entity (in example below, payment)
loan-payment paymentloan
If a loan entity is deleted, then all its associated payment entities must be deleted also.
2.52
Design IssuesDesign Issues
Use of entity sets vs. attributesChoice mainly depends on the structure of the enterprise being modeled, and on the semantics associated with the attribute in question.
Use of entity sets vs. relationship setsPossible guideline is to designate a relationship set to describe an action that occurs between entities
Binary versus n-ary relationship setsAlthough it is possible to replace any nonbinary (n-ary, for n > 2) relationship set by a number of distinct binary relationship sets, a n-ary relationship set shows more clearly that several entities participate in a single relationship.
Placement of relationship attributes
2.53
Weak Entity SetsWeak Entity Sets
An entity set that does not have a primary key is referred to as a weak entity set.
The existence of a weak entity set depends on the existence of a identifying entity set it must relate to the identifying entity set via a total, one-
to-many relationship set from the identifying to the weak entity set
Identifying relationship depicted using a double diamond
2.54
Weak entity …Weak entity …
The discriminator (or partial key) of a weak entity set is the set of attributes that distinguishes among all the entities of a weak entity set.
The primary key of a weak entity set is formed by the primary key of the strong entity set on which the weak entity set is existence dependent, plus the weak entity set’s discriminator.
2.55
Weak Entity Sets (Cont.)Weak Entity Sets (Cont.) Notation : see figure payment-number – discriminator of the
payment entity set Primary key for payment – (loan-number,
payment-number)
2.56
2.57
• shows weak entity depending on two strong entities.• Taken from Elmasri/Navathe’s book
2.58
EXTENDED E-R MODELEXTENDED E-R MODEL
extensions to capture more meaning
concepts of generalization, aggregation and sub-set hierarchies added Similar to OO concepts : inheritance, composite objects
2.59
GeneralizationGeneralization
to generalize from two or more entity sets and factor out commonality
Example : given two entities Faculty and Non-faculty, we can define a ‘general’ entity called Employee
Common attributes are factored out to define ‘Employee’ entity; specific (non-common) attributes incorporated in ‘Faculty’ and ‘Non-faculty’ entities
Also called as IS-A relationship A bottom-up design process – combine a number
of entity sets that share the same features into a higher-level entity set.
2.60
2.61
Another example :
2.62
SpecializationSpecialization
also called subset hierarchy; we create special cases for a given entity Teacher as a special case of Employee
entity E1 is subset of E if every instance of E1 is also an instance of E; this is also IS-A relationship
every instance in E need not be present in subsets of E
E called superset and E1 as subset (or sub-class
2.63
Specialization…..Specialization…..
specialization allows classification of an entity into subsets based on some distinguishing attribute/property
we may have several specialization of same entity
the subsets may have additional attributes
2.64
2.65
SpecializationSpecialization
Top-down design process; we designate subgroupings within an entity set that are distinctive from other entities in the set.
These subgroupings become lower-level entity sets that have attributes or participate in relationships that do not apply to the higher-level entity set.
Depicted by a triangle component labeled ISA (E.g. customer “is a” person).
2.66
InheritanceInheritance
there is inheritance of attributes from superclass or superset
the subclass/subset automatically inherits attributes defined at superclass/superset level
They also inherit relationship participations of higher levels
thus, inheritance present in both Generalization and specialization Direction important : bottom-up in generalization, top-
down in Specialization
Important to distinguish the two cases
2.67
Design Constraints on a Design Constraints on a Specialization/GeneralizationSpecialization/Generalization
Constraint on which entities can be members of a given lower-level entity set. condition-defined
E.g. all customers over 65 years are members of senior-citizen entity set; senior-citizen ISA person.
user-defined
2.68
Constraints …Constraints …
Constraint on whether or not entities may belong to more than one lower-level entity set within a single specialization. Disjoint
an entity can belong to only one lower-level entity set
Noted in E-R diagram by writing disjoint next to the ISA triangle
Overlapping
an entity can belong to more than one lower-level entity set
2.69
Design Constraints …Design Constraints …
Completeness constraint -- specifies whether or not an entity in the higher-level entity set must belong to at least one of the lower-level entity sets within a specialization. total : an entity must belong to one of the lower-level
entity sets partial: an entity need not belong to one of the lower-level
entity sets
2.70
AggregationAggregation
for building complex entity from existing entities (or existing entities and relationships)
two ways of defining complex entities : create an attribute whose value is another entity
define an entity as containing a group of related entities
2.71
Examples :Examples :
Work-order object (entity) defined as consisting of entities Raw-material, Tools and Workers;
Work-order itself related with Customer entity
Aggregation notation not explicitly provided in Extended E-R model
2.72
Raw Material Tools
Worker
Customer
JobNo Quantity
Work-order
2.73
AggregationAggregation
Consider the ternary relationship works-on, which we saw earlier
Suppose we want to record managers for tasks performed by an employee at a branch
2.74
Aggregation (Cont.)Aggregation (Cont.)
Relationship sets works-on and manages represent overlapping information Every manages relationship corresponds to a works-on
relationship
However, some works-on relationships may not correspond to any manages relationships
So we can’t discard the works-on relationship
Eliminate this redundancy via aggregation as shown in the following diagram : An employee works on a particular job at a particular branch
An employee, branch, job combination may have an associated manager
2.75
E-R Diagram With AggregationE-R Diagram With Aggregation
2.76
E-R Design DecisionsE-R Design Decisions
The use of an attribute or entity set to represent an object.
Whether a real-world concept is best expressed by an entity set or a relationship set.
The use of a ternary relationship versus a pair of binary relationships.
The use of a strong or weak entity set. The use of specialization/generalization –
contributes to modularity in the design. The use of aggregation – can treat the aggregate
entity set as a single unit without concern for the details of its internal structure.
2.77
E-R Diagram for a Banking EnterpriseE-R Diagram for a Banking Enterprise
2.78
Exercise: Airport database Exercise: Airport database
keeps track of airplanes, their owners, airport employees and pilots
Each airplane has a registration number, is of a particular plane type and is stored in a particular hanger. Each plane type has a model number, capacity and weight. Each hanger has a number, capacity and location. The database also keeps track of who owns which plane. Persons have name, address and phones. A person buys a plane on a particular date and cost.
2.79
Airport database….Airport database….
Each plane undergoes service many times. A service information contains date of work, nature, hours spent, cost, etc. Pilots and employees are persons. Pilots have a license number with validity and salary. Employees have a number, rank and salary. Each pilot is authorized to fly certain types of planes. Employees are involved in servicing of planes.
prepare E-R model
2.80
Exercise : Portfolio ManagementExercise : Portfolio Management
for individual investors
investments are made in shares, debentures, bonds, National saving certificates, various schemes like PPF, ELSS, mutual funds, etc.
these may be acquired at public issue time, purchased from market, obtained as bonus (free), on ‘rights-basis’, etc.
2.81
Portfolio …Portfolio …
some investments have regular returns; e.g., yearly, 6-monthly, etc. at fixed or announced rates
these will be sold in market or re-deemed, converted, etc.
how, when and how much invested, what returns already obtained are important for the investor to know how good are his investments. At year end, he may wants to know the market value of his investments
OO ModelingOO Modeling
2.83
Class and ObjectsClass and Objects
- Class:
- A class describes a set of objects that share the same attributes and behavior.
- A Class represents a concept within a system being modeled.
- Object:
- An Object is an instance of a Class
- An object is an entity with a well defined boundary and identity that encapsulates state and behavior
2.84
Class RepresentationClass Representation
- Class:
- A Class represents a concept within a system being modeled.
- A class is a named description of both the data structure and behavior of a set of objects
- An object instantiated from a class is a direct instance of a class and an indirect instance of the ancestors of the class
- Abstract Class
- Some classes may not be directly instantiated but are used to described the data structure and sometimes partial behavior of its descendants. These are called abstract classes
- Mostly used in design patterns and framework implementation
2.85
Object PerspectivesObject Perspectives
An object could be viewed from two related perspectives
An entity at a particular point in time with a specific value
As a holder of identity that has different values over time
First perspective is a snapshot perspective, which represents the system at a point in time.
Second perspective is Collaboration perspective in which the object has runtime relationships with other objects
2.86
Object RepresentationObject Representation
Each object has its own unique identity Each object may be referenced by a unique handle that
identifies the object and provides access to it An object contains one attribute slot for each attribute in its
full descriptor (class and every ancestor class) When instantiation and initialization of an object completes,
each attribute slot contains a value that is an instance of the classifier declared as the attribute type.
2.87
Object Representation (Cont’d)Object Representation (Cont’d)
As the system executes, the value in an (any) attribute slot may change, unless the attribute changeability property forbids (e.g. final) it to change
An object may be called to execute any operation that appears in its direct class (direct and inherited)
An object may be used as the value of any variable or parameter whose declared type is the same class or an ancestor of the direct class of the object (leads to polymorphism)
2.88
VisibilityVisibility
Visibility declares the ability of a modeling element to reference an element that is in a different namespace from the referencing element.
Visibility is part of the relationship between an element and the container that holds it.
Visibility Enumeration
Public: Any referencing element that can see the container can also see the indicated element
Protected: Only elements within the container or descendant of the container can see the indicated element
Private: Only the elements within the container can see the indicated element, other referencing elements or descendants of the container may not see the indicated element
2.89
Abstraction & EncapsulationAbstraction & Encapsulation
Abstraction is the act of identifying the essential characteristics of a thing that distinguish it from all other things Focus on relevant and important characteristics Focus upon externally visible aspects Used to deal with complexities
Encapsulation is hiding of internal complexity The technique of encapsulating software design decisions
in modules in such a way that the module's interfaces reveal as little as possible about the module's inner workings; thus each module is a 'black box' to the other modules in the system
2.90
Abstraction & EncapsulationAbstraction & Encapsulation
Abstraction can be (and often is) used as a technique for identifying which information should be hidden.
e.g. we might say that it is important to be able to add items to a list, but the details of how that is accomplished are not of interest and should be hidden.
2.91
Inheritance (Specialization)Inheritance (Specialization)
Inheritance is the mechanism by which more specific elements incorporate the structure and behavior defined by more general elements
Inheritance allows a full description to be constructed based upon generalization hierarchy
Conflict can occur for languages that support multiple inheritance (same operation in multiple ancestors, implemented differently). This results into ill formed models and should be avoided
Languages like Java do not support multiple inheritance and instead suggest to implement the interface, where the operations must be implemented by the implementing class
2.92
OO Application as a Collection of ObjectsOO Application as a Collection of Objects
Object Oriented Applications are collection of objects
Objects interact with each other to accomplish a task
Objects interact with each other by getting handle to the other objects
UML ModelingUML Modeling
2.94
UMLUML
UML: Unified Modeling Language
UML has many components to graphically model different aspects of an entire software system
UML Class Diagrams correspond to E-R Diagram, but several differences.
2.95
System ModelingSystem Modeling
Structural Models Class Diagram
Behavioral Models Interaction Diagram (Sequence, Collaboration)
State Chart Diagram
2.96
Class DiagramClass Diagram
Backbone of almost every object-oriented system model
Describes the static structure of a system
Provide a conceptual model of the system in terms of entities and their relationships
2.97
ClassClass
Each class is represented by a rectangle subdivided into three compartments Name Attributes Operations
Modifiers are used to indicate visibility of attributes and operations. ‘+’ is used to denote Public visibility (everyone) ‘#’ is used to denote Protected visibility (friends and derived) ‘-’ is used to denote Private visibility (no one)
By default, attributes are hidden and operations are visible. The last two compartments may be omitted to simplify the class
diagrams
2.98
Class Diagram (Relationships)
•There are two kinds of Relationship•Generalization (parent-child relationship)
•Association (student enrolls in course)
•Associations can be further classified as•Aggregation
•Composition
2.99
An example of Class An example of Class
Account_Name- Custom_Name- Balance
+AddFunds( )+WithDraw( )+Transfer( )
Name
Attributes
Operations
2.100
Association RelationshipAssociation Relationship
Association is the most common relationship in a class diagram
Association shows relationship between instances of the classes
Association could have Name
End Names (Roles)
Multiplicity
NavigabilityAssociation Name
Role
MultiplicityNavigable
2.101
Multiplicity and Roles Multiplicity and Roles
University Person
1 *
Multiplicity
Symbol Meaning
1 One and only one
0..1 Zero or one
M..N From M to N (natural language)
* From zero to any positive integer
0..* From zero to any positive integer
1..* From one to any positive integer
Role
Role
A given student belongs to a single university;
An university can have zero to any number of students
student
Multiplicity
2.102
Whole – Part RelationshipWhole – Part Relationship
Association shows structural relationship between two classes, conceptually at peer level (Employee works for Employer)
Sometimes the relationship could be “whole-part” or “has” (e.g. A car has engine, A Company has Departments)
This is represented using aggregation or composition
2.103
Class Relationships: Class Relationships: AggregationAggregation
Class C
Class E1 Class E2
AGGREGATION
Aggregation: expresses a relationship among instances of related classes. It is a specific kind of Container-Containee relationship.
It expresses a relationship where an instance of the Container-class has the responsibility to hold and maintain instances of each Containee-class that have been createdoutside the auspices of the Container-class.
Aggregation should be used to express a more informalrelationship than composition expresses. That is, it is anappropriate relationship where the Container and its Containees can be manipulated independently.
Aggregation is appropriate when Container and Containeeshave no special access privileges to each other.
Container Class
Containee Classes
Bag
Apples Milk
Example
2.104
Class Relationships: Composition
Class W
Class P1 Class P2
COMPOSITION Composition: expresses a relationship among instances of related classes. It is a specific kind of Whole-Part relationship.
It expresses a relationship where an instance of the Whole-class has the responsibility to create and initialize instances of each Part-class.
It may also be used to express a relationship where instancesof the Part-classes have privileged access or visibility tocertain attributes and/or behaviors defined by theWhole-class.
Composition should also be used to express relationship where instances of the Whole-class have exclusive access to and control of instances of the Part-classes.
Composition should be used to express a relationship wherethe behavior of Part instances is undefined without beingrelated to an instance of the Whole. And, conversely, thebehavior of the Whole is ill-defined or incomplete if one or more of the Part instances are undefined.
Whole Class
Part Classes
Automobile
Engine Transmission
Example
2.105
Aggregation vs. CompositionAggregation vs. Composition
•CompositionComposition is really a strong form of aggregation •components have only one owner •components cannot exist independent of their owner •components live or die with their owner e.g. Each car has an engine that can not be shared with other cars.
•Aggregations may form "part of" the aggregate, but may not be essential to it. They may also exist independent of the aggregate. e.g. Apples may exist independent of the bag.
Composition and Aggregation are special forms of associationSo all properties of association also apply (role, multiplicity)
2.106
IS-A RelationshipIS-A Relationship
Association shows structural relationship between two classes, conceptually at peer level
Aggregation / Composition shows whole-part relationship
Sometimes the relationship between two classes is IS-A relationship (e.g. Dog is an Animal, Student is a Person)
Specialization-Generalization shows IS-A Relationship
2.107
Subtype2
Supertype
Subtype1
Class Relationships: Generalization
Generalization expresses a relationship among related classes. It is a class that includes its subclasses.
Regular Customer
Loyalty Customer
Customer Example:
Regular Customer
Loyalty Customer
Customer or:
GeneralizedClass
SpecializedClass
2.108
Class Diagram – An ExampleClass Diagram – An Example
Order
-dateReceived-isPrepaid
-number :String-price : Money
+dispatch()+close()
Customer
-name-address
+creditRating() : String()
Corporate Customer
-contactName-creditRating-creditLimit
+remind()+billForMonth(Integer)
Personal Customer
-creditCard#
OrderLine
-quantity: Integer-price: Money
-isSatisfied: Boolean
Product* 1
1
*Employee
*0..1
{if Order.customer.creditRating is"poor", then Order.isPrepaid must
be true }
* 1
Constraint
(inside braces{}}
Operations
Attributes
Name
Association
Multiplicity: mandatory
Multiplicity: Many value
Multiplicity: optional
Generalization
class
Aggregation
2.109
Association – Advanced ConceptsAssociation – Advanced Concepts
Sometimes an Association could have attributes as well as behavior
E.g. student enrolls for a course, enrollment can have attribute like grade
Attribute valued associations are represented through association class
Sometimes an association can show relationship between more than two classes
This is represented through N-Ary Association
2.110
Association Class
•Association Class shows relationship between two classes and also allows to add attributes and operations to associations
Derived Attribute
Attributes
Method
Association Class
2.111
N-ARY ASSOCIATION•N-Ary Association Class shows relationship between more than two classes and also allows to add attributes and operations to associations
N-Ary AssociationClass
2.112
Type Independent BehaviorType Independent Behavior
Sometimes it is necessary to write an algorithm that works for many different types of elements
The purpose is to capture generalized behavior without caring for which particular type of object it refers to
This could be achieved using parameterized or template class
This is strictly not an IS-A relationship
Template class shows generalized behavior for unbounded type
Implementing class bind to it specifying the binding type
2.113
PARAMETERIZED/TEMPLATE CLASS
-Template Classes help to show generalized behavior-Some other class binds to a template class
Type Parameter
Template Class
Binding For Parameter
Bound Class
2.114
UML Extensibility - StereotypesUML Extensibility - Stereotypes
UML is extensible
You can create your own Stereotypes and attach meaning to it
Two such widely used stereotypes are
Abstract Class
Interface
2.115
Generalization : Showing Abstract Class
Italics Show AbstractAll Concrete class mustImplement this method
Concrete Class
2.116
Interface: Extend and Implement
Interface
Realization
Implementing Class
2.117
Exercise 1 – Class RelationshipsExercise 1 – Class Relationships
An internal fund transfer system allows the funds to be transmitted between two different accounts held within the same accounting system.
It caters to two types of customers: Remitter and Beneficiary. A remitter or beneficiary can hold multiple accounts.
A payment instruction need to contain details about Remitter, Beneficiary, value Date of the payment and amount. A payment instruction can have one debit account and multiple credit accounts.
SHOW A CLASS DIAGRAM CAPTURING THE ABOVE DETAILS.
SHOW
ASSOCIATION,
SPECIALIZATION/GENERALIZATION,
AGGRAGATION
2.118
Solution – Exercise 1Solution – Exercise 1
2.119
Exercise 2 – Association ClassExercise 2 – Association Class
A student can enroll for minimum 3 and maximum 7 courses.
A course can have no enrollments or a maximum of 50 students enrolling for it.
Each student enrollment needs keep information about enrollment date and grade
Show a class diagram showing association class and possible attributes and behavior of the association class
2.120
Solution – Exercise 2Solution – Exercise 2
2.121
Exercise 3 – Aggregation / CompositionExercise 3 – Aggregation / CompositionA team builds cars
A team can consist of zero or more sub-teams
A team can have one or more employees, An employee can be part of zero or more teams
A Car can have one or more components. A component must be part of one car only
A component is an assembly An assembly can have zero or more sub-assemblies.
(When a team/sub-team is not building cars, it may build other vehicles
Sub-assemblies are not usable outside their assembly component)
Use the above information to draw a class diagram and show aggregation and composition relationships
2.122
Solution – Exercise 3Solution – Exercise 3
2.123
Behavioral Models - OverviewBehavioral Models - Overview
• Collaboration Diagram
Collaboration diagrams show the runtime relationship between objects.
• Sequence Diagram
Sequence diagrams show how the objects interact to perform the behavior of a use case, it shows the interaction among objects in time sequence
• State Chart Diagram
• Shows sequence of states an object goes through, events that cause a transition and the actions that result from a state change. E.g. transaction life cycle
2.124
Sequence DiagramSequence Diagram
Boundary Class Control Class Entity Class
2.125
Collaboration DiagramCollaboration Diagram
2.126
State Chart DiagramState Chart Diagram
2.127
Requirements ModelingRequirements Modeling
Use Case Diagram
Activity Diagram
2.128
Use Case DiagramUse Case Diagram
Used for describing a set of user scenarios
Mainly used for capturing user requirements
Works like a contract between end user and software developers
2.129
Use Case Diagram (core components)
Actors: A role that a user plays with respect to the system,including human users and other systems. e.g.,inanimate physical objects (e.g. robot); an external system that needs some information from the current system.
Use case: A set of scenarios that describes an interaction between a user
and a system, including alternatives.
System boundary: rectangle diagram representing the boundary between the actors and the system.
2.130
Use Case Diagram(core relationship)Use Case Diagram(core relationship)
Association: communication between an actor and a use case; Represented by a solid line.
Generalization: relationship between one general use case and a special use case (used for defining special alternatives)Represented by a line with a triangular arrow head toward the parent use case.
2.131
Use Case Diagram(core relationship)Use Case Diagram(core relationship)
Extend: a dotted line labeled <<extend>> with an arrow toward the base case. The extending use case may add behavior to the base use case. The base class may declare “extension points”.
<<extend>>
Include: a dotted line labeled <<include>> beginning at base use case and ending with an arrows pointing to the include use case. The include relationship occurs when a chunk of behavior is similar across more than one use case. Use “include” in stead of copying the description of that behavior.
<<include>>
2.132
2.133
Activity DiagramActivity Diagram
The workflow of a use case is described using activity diagram
2.134
Activity Diagram – e Commerce SystemActivity Diagram – e Commerce System
2.135
ReferencesReferences
UML Distilled: A Brief Guide to the Standard Object Modeling LanguageUML Distilled: A Brief Guide to the Standard Object Modeling LanguageMartin Fowler, Kendall ScottMartin Fowler, Kendall Scott
The Unified Modeling Language Reference ManualThe Unified Modeling Language Reference ManualJames Rumbaugh, Ivar Jacobson, Grady BoochJames Rumbaugh, Ivar Jacobson, Grady Booch
The Unified Modeling Language User GuideThe Unified Modeling Language User GuideJames Rumbaugh, Ivar Jacobson, Grady BoochJames Rumbaugh, Ivar Jacobson, Grady Booch
2.136
Reduction of an E-R Schema to TablesReduction of an E-R Schema to Tables
Primary keys allow entity sets and relationship sets to be expressed uniformly as tables which represent the contents of the database.
A database which conforms to an E-R diagram can be represented by a collection of tables.
For each entity set and relationship set there is a unique table which is assigned the name of the corresponding entity set or relationship set.
2.137
Reduction of an E-R Schema …Reduction of an E-R Schema …
Each table has a number of columns (generally corresponding to attributes), which have unique names.
Converting an E-R diagram to a table format is the basis for deriving a relational database design from an E-R diagram.
2.138
Representing Entity Sets as TablesRepresenting Entity Sets as Tables
A strong entity set reduces to a table with the same attributes.
2.139
Composite and Multivalued AttributesComposite and Multivalued Attributes
Composite attributes are flattened out by creating a separate attribute for each component attribute E.g. given entity set customer with composite attribute name
with component attributes first-name and last-name the table corresponding to the entity set has two attributes name.first-name and name.last-name
2.140
Composite and Multivalued Attributes …Composite and Multivalued Attributes …
A multivalued attribute M of an entity E is represented by a separate table EM Table EM has attributes corresponding to the primary
key of E and an attribute corresponding to multivalued attribute M
E.g. for dependent-names of employee
employee-dependent-names( employee-id, dname)
Each value of the multivalued attribute maps to a separate row of the table EM
E.g., an employee John with two dependents Johnson and Johndotir maps to two rows: (John, Johnson) and (John, Johndotir)
2.141
Representing Weak Entity SetsRepresenting Weak Entity Sets
A weak entity set becomes a table that includes a column for the primary key of the identifying strong entity set
2.142
Representing Relationship Sets as Representing Relationship Sets as TablesTables
A many-to-many relationship set is represented as a table with columns for the primary keys of the two participating entity sets, and any descriptive attributes of the relationship set.
E.g.: table for relationship set borrower
2.143
Redundancy of TablesRedundancy of Tables
Many-to-one and one-to-many relationship sets that are total on the many-side can be represented by adding an extra attribute to the many side, containing the primary key of the one side
E.g.: Instead of creating a table for relationship account-branch, add an attribute branch to the entity set account
2.144
Redundancy of Tables (Cont.)Redundancy of Tables (Cont.)
For one-to-one relationship sets, either side can be chosen to represent the relationship by including key of the other side
If participation is partial on the many side, replacing a table by an extra attribute in the relation corresponding to the “many” side could result in null values
The table corresponding to a relationship set linking a weak entity set to its identifying strong entity set is redundant.
2.145
Representing Specialization as TablesRepresenting Specialization as Tables Method 1:
Form a table for the higher level entity
Form a table for each lower level entity set, include primary key of higher level entity set and local attributes
table table attributespersonname, street, city customer name, credit-ratingemployee name, salary
Drawback: getting information about, e.g., employee requires accessing two tables
2.146
Representing Specialization as Tables Representing Specialization as Tables (Cont.)(Cont.)
Method 2: Form a table for each entity set with all local and inherited
attributestable table attributes
personname, street, citycustomername, street, city, credit-ratingemployee name, street, city, salary
2.147
If specialization is total, table for generalized entity (person) not required to store information
Can be defined as a “view” relation containing union of specialization tables
But explicit table may still be needed for foreign key constraints
Drawback: street and city may be stored redundantly for persons who are both customers and employees
2.148
Relations Corresponding to Relations Corresponding to AggregationAggregation
To represent aggregation, create a table containing
primary key of the aggregated relationship,
the primary key of the associated entity set
Any descriptive attributes
2.149
Relations Corresponding to Relations Corresponding to Aggregation (Cont.)Aggregation (Cont.)
E.g. to represent aggregation manages between relationship works-on and entity set manager, create a table manages(employee-id, branch-name, title, manager-name)
Table works-on is redundant provided we are willing to store null values for attribute manager-name in table manages