MAPPING MODELS TO CODE - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

MAPPING MODELS TO CODE

Description:

Navigability arrow pointing from source object to target object indicates that ... Design Model Class Diagram: Navigability arrow points from (Register) to target ... – PowerPoint PPT presentation

Number of Views:54
Avg rating:3.0/5.0
Slides: 43
Provided by: beyhana
Category:

less

Transcript and Presenter's Notes

Title: MAPPING MODELS TO CODE


1
MAPPING MODELS TO CODE
2
Model Transformation
  • The purpose of object model transformation is to
    simplify or optimize the original model.
  • Development process is a series of model
    transformations, starting with the analysis model
    and ending with the object design model, adding
    solution domain details along the way.
  • eBook(Chapter 20) Implementation Model Mapping
    Designs To Code

3
Model Transformation
Object design model before transformation
Advertiser
Player
LeagueOwner
emailAddress
emailAddress
emailAddress
Object design model after transformation
User
emailAddress
Player
Advertiser
LeagueOwner
4
Design Model -gt Implementation Model
  • The design model (Interaction diagrams and Design
    Class Diagrams (DCD) ) created during object
    design is used to generate the implementation
    model which may contain
  • Source code (class, interface, and method
    definitions)
  • Data Model (database schemas and mappings of
    persistence objects)
  • JSP/XML/HTML pages
  • etc.

5
Mapping Attributes to Java code
6
Method signatures and constructor
1
productSpec
  • Java constructor SalesLineItem(...) is derived
    from create(spec,qty) message sent to a
    SalesLineItem in the enterItem interaction
    diagram.
  • This indicates, in Java, that a constructor
    supporting these parameters is required.
  • The create method is often excluded from the
    class diagram.

7
Creating Methods from Interaction Diagrams
8
Creating Methods from Interaction Diagrams
catalog
1
sale
1
9
Creating Methods from Interaction Diagrams
10
Creating Methods from Interaction Diagrams
11
Associations
  • Associations are UML concepts that denote links
    between two or more objects.
  • OOP languages do not have the concept of an
    association instead they provide
  • References one object stores a handle to another
    object
  • Collections references to several objects that
    can be stored and ordered
  • Associations are realized in terms of references,
    taking into account the multiplicity of the
    association and their direction.
  • In domain models the association name is used,
    but in design class diagrams, it is often
    excluded.
  • Navigability arrow pointing from source object to
    target object indicates that source object has
    one target object as an attribute.

12
Mapping Associations to Java code
Domain Model Class Diagram The association name
(Captures-current-sale is used because of the
conceptual perspective.
Register
Sale
1
  • Captures-current-sale

1
...
...
Design Model Class Diagram Navigability arrow
points from (Register) to target (Sale) object,
indicating a Register object has an attribute of
Sale.
Register
Sale
1
currentSale Sale
currentSale
...
...
Public class Register private Sale
currentSale
13
Collection Classes
lineItems
1..
  • 1-to-Many relationships are usually implemented
    with a collection object, such as List or Map.
  • For example, the Java libraries contain
    collection classes such as ArrayList and HashMap
    which implement List and Map interfaces.

14
Storage Mechanisms and Persistence Objects
  • Persistent objects have to be mapped to data
    structures that can be stored by a persistent
    storage.
  • There are 3 types of storage mechanism for
    persistent objects
  • Object databases no additional persistence
    service is required
  • Relational databases mismatch between
    record-oriented and object-oriented
    representations of data should be handled.
    Object-to-Relational (OR) mapping service is
    required.
  • Other such as flat files, XML structures. Like
    relational databases, a representation mismatch
    exists between objects and these
    non-object-oriented formats, and special
    persistence services are required to make them
    work with objects.

15
Hard-coding SQL in domain classes
  • SQL is embedded in domain class code.
  • Directly couples domain classes with the schema
    of the relational database.
  • A change such as renaming a column or porting to
    another database will result in change in the
    source code of the domain classes (tight
    coupling).

16
Hard-coding SQL in data classes
  • SQL statements for domain classes are
    encapsulated in data classes.
  • Developing stored procedures in the database to
    represent objects (replacing data classes).

17
Persistence Layer
  • Persistence layer maps objects to a persistence
    mechanism, such as a relational database.
  • The application classes do not have to know about
    the schema and how the objects are stored in the
    database (seperation of concern).

18
Persistence Framework
  • Persistence framework is a general-purpose,
    reusable, and extendable set of types that
    provides functionality to support persistent
    objects.
  • A persistence service such as O-R mapping service
    provides the actual service to translate objects
    into records for storing and translate records
    into objects for retrieving.
  • Hibernate is an open-source persistence framework
    which is used widely in the Java domain.
    (www.hibernate.org)

19
Mapping Objects to a Schema
  • In relational databases, a schema describes the
    valid set of data records that can be stored in
    the database.
  • In UML, class diagrams are used to describe the
    set of valid instances that can be created by the
    source code.
  • Relational databases store persistent data in the
    form of tables (relations).
  • A table is structured in columns, each of which
    represents an attribute.

20
Mapping Objects to a Schema
  • User table has three colums
  • login attribute can be used as a primary key

Primary key
login
email
fi
r
stName
am384
am384_at_mail.org
alice
js289
john_at_mail.de
john
bd
bobd_at_mail.ch
bob
Candidate key
Candidate key
User table
21
Mapping Objects to a Schema
  • Foreign key is an attribute that references the
    primary key of another table, and it links a data
    record in one table with one or more records in
    another table.

League table
login
name
am384
tictactoeNovice
am384
tictactoeExpert
js289
chessNovice
Foreign key referencing User table
22
Mapping Objects to a Schema
  • Map each class to a table with the same name.
  • For each attribute, add a column in the table
    with the same name of the attribute in the class.
  • Each data record in the table corresponds to an
    instance of the class.
  • By keeping the names in the object model and the
    relational schema consistent, we provide
    traceability between both representations and
    make future changes easier.
  • For primitive types, the correspondence between
    the programming language type and the database
    type is trivial (Java Date type maps to datetime
    type in SQL.
  • However, the other types such as String, the
    mapping is more complex type text in SQL
    requires a specified maximum size, such as
    text25.

23
Selection of Primary Key
  • There are 2 options when selecting a primary key
    for a table
  • Identify a set of class attributes that uniquely
    identifies the object login name primary key
  • Drawbacks
  • If the value of the login attribute changes, we
    need to update all tables where it is a foreign
    key.
  • If we want to store users from different Arenas
    (login names are unique only within a single
    Arena), we would need to add the name of the
    Arena in the primary key.

24
Selection of Primary Key
  • Use an arbitrary unique identifier (id) attribute
    as a primary key. Generate the id attribute for
    each object (some database systems provide
    feaures for automaticall generating ids).
  • Increment id every time an object is created.

User
firstNameString
loginString
emailString
User table
idlong
firstNametext25
logintext8
emailtext32
25
Mapping Associations to Database Schemas
  • The mapping of the association depends on the
    multiplicity of the association
  • 1-to-1 and 1-to-many associations are implemented
    as a buried association using a foreign key.
  • Many-to-many associations are implemented as a
    separate table.

26
Buried Associations
  • For 1-to-many associations, add a foreign key to
    the table representing class on the many end.
  • For all other associations, select either class
    at the end of association.

27
Buried Associations
  • Add owner column to the League table referring to
    the primary key of the LeagueOwner table.
  • Value of the owner column is the value of the id
    (i.e. primary key) of the corresponding league.
  • If there are multiple Leagues owned by the same
    LeagueOwner, multiple data records of the League
    table have the id of the owner as value for this
    column.

1

League
LeagueOwner
LeagueOwner table
League table
idlong
o
wnerlong
...
...
idlong
28
Mapping Associations - Separate Table
  • Many-to-many associations are implemented using a
    separate two-column table, called association
    table, with foreign keys for both classes of the
    association.
  • Each row in the association table corresponds to
    a link between two instances.

29
Mapping Associations - Separate Table
  • Map many-to-many Tournament/Player association to
    an association table with two columns.
  • id of the Tournaments
  • id of the Player



Player
Tournament
TournamentPlayerAssociation table
Tournament table
Player table
id
tournament
pla
y
er
name
...
id
name
...
23
23
no
vice
56
alice
56
24
e
xper
t
79
john
23
79
30
Mapping Associations - Separate Table
  • If a player is part of multiple Tournaments, each
    Player/Tournament association will have separate
    record.
  • If a Tournament includes multiple players, each
    player will have a separate data record.
  • Association table contains two links representing
    the membership of alice and john in the
    novice Tournament.



Player
Tournament
TournamentPlayerAssociation table
Tournament table
Player table
id
tournament
pla
y
er
name
...
id
name
...
23
23
no
vice
56
alice
56
24
e
xper
t
79
john
23
79
31
Mapping inheritance relationships
  • There are 2 main options for mapping an
    inheritance relationship to a database schema
  • Vertical mapping map superclass and subclasses
    to individual tables (similar to 1-to-1
    association mapping).
  • Horizontal mapping push the attributes of the
    superclass down into subclasses, effectively
    removing the need for a superclass table. Each
    subclass table duplicates the columns of the
    super-class.

32
Mapping inheritance relationship with vertical
mapping
  • Superclass table includes a column for each
    attribute defined in the superclass and an
    additional column for subclass that corresponds
    to the data record.
  • All tables share the same primary key identifier
    of the object.
  • Data records in the superclass, and subclass
    tables with the same primary key value refer to
    the same object.

33
Mapping inheritance relationship with vertical
mapping
User
name
Player
LeagueOwner
maxNumLeagues
credits
User table
id
name
...
r
ole
56
z
oe
LeagueOwner
79
john
Pla
y
er
LeagueOwner table
Player table
id
maxNumLea
gues
...
id
credits
...
56
12
79
126
34
Mapping inheritance relationship with vertical
mapping
  • The classes User, LeagueOwner, and Player are
    each mapped to a table with columns for the
    attributes of the classes.
  • User table includes an additional column, role
    which donates the class of the data record.
  • User Zoe is a LeagueOwner who can lead at most 12
    Leagues
  • User John is a Player who won 126 credits
  • To retrieve an object from the database, examine
    the first data record in the superclass table
    which includes the attribute values for the
    superclass and subclass of the instance.
  • By using the same object id query the subclass
    and retrieve the remainder of the attribute
    values.

35
Mapping inheritance relationship with horizontal
mapping
User
name
Player
LeagueOwner
maxNumLeagues
credits
LeagueOwner table
Player table
id
...
id
...
maxNumLeagues
credits
name
name
56
12
79
126
z
oe
john
  • LeagueOwners table and Players table includes a
    column for its own attributes and for attributes
    of the User class.
  • A single query to retrieve all attributes for an
    object is sufficient.

36
Mapping inheritance relationships trade-offs
  • The trade-off between using a separate table for
    superclasses and duplicating columns in the
    subclass tables is between modifiability and
    response time
  • Separate table add attributes to the superclass
    simply by adding a column to the superclass
    table. When adding a subclass, add a table for
    the subclass with a column for each attribute in
    the subclass.
  • Duplicating columns modifying the database
    schema is more complex, but individual objects
    are not fragmented across a number of tables,
    which results in faster queries.
  • We need to examine likelihood of change against
    the performance requirements.

37
Mapping contracts to exceptions
  • Exception mechanism can be used for signaling and
    handling contract violations.
  • In Java, we raise an exception with the throw
    keyword followed by an exception object.
  • Throwing an exception interrupts the control flow
    and unwinds the call stack until a matching catch
    statement is found.
  • catch statement is followed by a parameter which
    is bound to the exception object and an exception
    handling block.
  • If the exception object is of the same type of
    the parameter, the catch statement matches, and
    the exception handling block is executed.

38
Mapping contracts to exceptions
Tournament
-maxNumPlayers int
precondition !isPlayerAccepted(p)
getNumPlayers()int
getMaxNumPlayers()int
isPlayerAccepted(pPlayer)boolean
addPlayer(pPlayer)
preconditiongetNumPlayers() ltgetMaxNumPlayers(
)
postconditionisPlayerAccepted(p)
39
Mapping contracts to exceptions
  • public class TournamentControl
  • private Tournament tournament
  • public void addPlayer(Player p) throws
    KnownPlayerException
  • if (tournament.isPlayerAccepted(p))
  • throw new KnownPlayerException(p)
  • //... Normal addPlayer behavior
  • public class TournamentForm
  • private TournamentControl control
  • private ArrayList players
  • public void processPlayerApplications()
  • // Go through all the players who applied for
    this tournament
  • for (Iteration i players.iterator()
    i.hasNext())
  • try
  • // Delegate to the control object.
  • control.acceptPlayer((Player)i.next())
  • catch (KnownPlayerException e)

40
Mapping contracts to exceptions
  • If acceptPlayer() operation of TournamentControl
    is invoked with a player who is already part of
    the Tournament, TournamentControl.addPlayer()
    throws an exception of type KnownPlayer which is
    cought by the caller, TournamentForm.addPlayer()
    which forwards the exception to the ErrorConsole
    class.
  • ErrorConsole boundary object then displays a list
    of error messages to the user.

41
Mapping contracts to exceptions
  • Pre-conditions should be checked at the
    beginning of the method, before any processing is
    done.
  • Post-conditions should be checked at the end of
    the method, after all the work has been
    completed. Each post-condition corresponds to a
    Boolean expression in an if statement that raises
    an exception if the contract is violated.
  • Invariants should be checked at the same time as
    post-conditions.

42
Mapping contracts to exceptions
  • If we mapped every contract, we would have a
    robust system, but it is not realistic
  • Coding effort
  • Increased opportunities for defects
  • Obfuscated code
  • Performance drawbacks
Write a Comment
User Comments (0)
About PowerShow.com