Vous êtes sur la page 1sur 33

Mapping Models To Code

M.Shafi Tokhi

TU­Berlin 2008

Software Engineering ­ project
Table of Contents
● An overview of mapping
● Mapping concept
● Optimizing the object model design
● Collapsing objects into attributes
● Mapping associations to collections
● Mapping object models to a relational database.
● Primary key, candidate key, foreign key
● Buried association
● Realizing Inheritance
● Comparing separate columns vs duplicate columns
● Summary
An Overview of Mapping

● Transformation is usually localized, affects a small 
number of classes, attributes, and operations, and is 
executed in a series of small steps.
● The transformations occur during numerous object 
design and implementation activities.
Mapping Concept

● Model transformation: operate on object models, e.g: a 
class with street, address,zip code and etc..
● Refactoring: improve a single aspect of a system, 
manipulate the source code.
● Forward Engineering: produces a source code template 
that corresponds to an object model.
● Reverse Engineering: produce a model that corresponds 
to source code.
Mapping Concept

Forward engineering

Reverse engineering

Model space Source code space
Model Transformation
● Applies to an object model and results in another 
object model [Blaha & Permerlani, 1998].
Object design model before transformation
LeagueOwner Advertiser Player
+email:Address +email:Address +email:Address

Object design model after transformation


LeagueOwner Advertiser Player


Before refactoring After refactoring
public class User {
public class Player { private String email;
private String email; }
//... public class Player extends User {
} //...
public class LeagueOwner { }
private String eMail; public class LeagueOwner extends
//... User {
} //...
public class Advertiser { }
private String email_address; public class Advertiser extends
User {
Forward Engineering
Object design model before transformation

User LeagueOwner
+email:String +maxNumLeagues:int

Source code after transformation
public class LeagueOwner extends User {
public class User { private int maxNumLeagues;
private String email; public int getMaxNumLeagues() {
public String getEmail() { return maxNumLeagues;
return email;
public void setMaxNumLeagues
public void setEmail(String value){
(int value) {
email = value;
} maxNumLeagues = value;
public void notify(String msg) { }
// .... /* Other methods omitted */
} }
/* Other methods omitted */
Mapping Activities

● Optimization
● Realizing associations
● Mapping contracts to exceptions
● Mapping class Models to a strong schema
Optimizing the Object Model Design
● Adding associations to optimize access paths.
–  prevent bottleneck performance.
–  Reduce many associations to one.
–  Remove excessive modeling (misplaced attributes).
● Collapsing objects into attributes (Figure in next slide).
● Delaying expensive computations.
● Caching the results of expensive computations.
Collapsing Objects into attributes

Object design model before transformation

Person SocialSecurity

Object design model after transformation

Mapping Associations to Collections

● Associations are UML concepts that denote collection 
of bidirectional links between two or more objects.
● OOP language do not support associations, they do 
support references instead.
● References are unidirectional, take place between two 
Mapping Associations
● Unidirectional one­to­one associations:
Object design model before transformation
1 1
Advertiser Account

Source code after transformation

public class Advertiser {

private Account account;
public Advertiser() {
account = new Account();
public Account getAccount() {
return account;
Realization of unidirectional one­to­one association
Mapping Associations
● Bidirectional one­to­one associations:
Object design model before transformation
1 1
Advertiser Account

Source code after transformation

public class Advertiser extends User{ public class Account {

/* The account field is initialized /* The owner field is initialized
* in the constructor and never * during the constructor and
* modified. */ * never modified. */
private Account account; private Advertiser owner;

public Account(owner:Advertiser) {
public Advertiser() {
this.owner = owner;
account = new Account(this); }
} public Advertiser getOwner() {
public Account getAccount() { return owner;
return account; }
} }
Realization of bidirectional one­to­one association
Mapping Associations
● One­to­many associations:
Object design model before transformation
1 *
Advertiser Account

Source code after transformation

public class Advertiser { public class Account {

private Set accounts; private Advertiser owner;
public Advertiser() { public void setOwner(Advertiser newOwner) {
accounts = new HashSet(); if (owner != newOwner) {
} Advertiser old = owner;
public void addAccount(Account a) { owner = newOwner;
accounts.add(a); if (newOwner != null)
a.setOwner(this); newOwner.addAccount(this);
} if (oldOwner != null)
public void removeAccount(Account a) { old.removeAccount(this);
accounts.remove(a); }
a.setOwner(null); }
} }

Realization of bidirectional one­to­many association
Mapping Associations
● Many­to­many associations:
Object design model before transformation
* {ordered} *
Tournament Player

Source code after transformation

public class Tournament { public class Player {

private List players; private List tournaments;
public Tournament() { public Player() {
players = new ArrayList(); tournaments = new ArrayList();
} }
public void addPlayer(Player p) { public void addTournament(Tournament t) {
if (!players.contains(p)) { if (!tournaments.contains(t)) {
players.add(p); tournaments.add(t);
p.addTournament(this); t.addPlayer(this);
} }
} }
} }
Realization of bidirectional many­to­many association
Mapping Associations
● Qualified association:

Object design model before transformation
* *
League Player

Object design model before forward engineering
* 0..1
League nickName Player
Mapping Associations
● Qualified association ( continued )

public class League {

private Map players;

public void addPlayer

(String nickName, Player p) { public class Player {
if (!players.containsKey(nickName)) private Map leagues;
players.put(nickName, p); public void addLeague
p.addLeague(nickName, this); (String nickName, League l) {
} if (!leagues.containsKey(l)) {
} leagues.put(l, nickName);
} l.addPlayer(nickName, this);

Realization of bidirectional qualified association
Transformation of an association class
Object design model before transformation


+ getTotalStat(name)
+ updateStats(match)

Tournament Player
* *

Object design model after transformation


+ getTotalStat(name)
+ updateStats(match)
1 1
Tournament Player
* *
Exception handling in Java
● Many object oriented languages including Java do not 
built­in support for contracts.
● we can use exceptions mechanism for building blocks for 
signaling and handling contract violations.
● In java we use try­throw­catch mechanism.
● Example:
– Assume the acceptPlayer() operation of TournamentControl 
is invoked with a player who is already part of the 
– In this case acceptPlayer() should throw an exception of 
type KnownPlayer. ( source code on next slide )
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.
} catch (KnownPlayerException e) {
// If an exception was caught, log it to the console, and
// proceed to the next player.
Implementing a contract
For each operation in the contract do the following steps:
● Checking preconditions: check preconditions at the 
beginning of the method and raise an exception if the 
precondition is fails.
● Checking postconditions: check postconditions at the end 
of the method and raise an exception if the contract is 
violated. ( corresponds to a boolean expression ).
● Check invariants: invariants are checked at the same time 
as postconditions.
● Dealing with inheritance: encapsulate the checking code 
for preconditions and postconditions into separate 
methods that can be called from subclasses.
Implementing a contract
getMaxNumPlayers() > 0


-maxNumPlayers: int
!isPlayerAccepted(p) +getMaxNumPlayers():int

getNumPlayers() < «postcondition»
getMaxNumPlayers() isPlayerAccepted(p)

A complete implementation of the Tournament.addPlayer() contract
download Tournament.java src !
Mapping object model to a relational 
● UML constructs must be mapped to a single relational 
database construct – the table.
● Each UML class is mapped to a table and each 
attribute is mapped to a column.
● Instance of a class represent a row in the table.
● A many­to­many association is mapped to it's own 
● A one­to­many association implemented as buried 
foreign key.
Mapping the User class to a database


User table
id:long firstName:text[25] login:text[8] email:text[32]
Primary key, Candidate key, Foreign key
Primary key
User table
FirstName login email
“alice” “am384” “am384@mail.org”
“john” “js289” “john@mail.de”
“bob” “bd” “bobd@mail.ch”
Candidate key Candidate key
League table
name login
“tictactoeNovice” “am384”
“tictactoeExpert” “am384”
“chessNovice” “js289”

Foreign key referencing User table
Buried association
● For one to­many association we put the foreign key on 
the class representing the many side.
● Association with multiplicity “one” can be implemented 
using a foreign key. Because the association vanishes 
in the table, we call this a buried association.

LeagueOwner 1 * League

LeagueOwner table League table
id:long ... id:long ... owner:long
Realizing Inheritance
● Relational databases do not support inheritance.
● Two possibilities to map UML inheritance relationships 
to a database schema
 With a separate table (vertical mapping)
➢ The attributes of the superclass and the 
subclasses are mapped to different tables
 By duplicating columns (horizontal mapping)
➢ There is no table for the superclass the subclass 
holds it's own and superclass attributes.
Realizing Inheritance with a sperate table


LeagueOwner Player
maxNumLeagues credits

User table
id name ... role

56 zoe LeagueOwner

79 john Player

LeagueOwner table Player table
id maxNumLeagues ... id credits ...

56 12 79 126
Realizing Inheritance by duplicating 


LeagueOwner Player
maxNumLeagues credits

LeagueOwner table Player table
id name maxNumLeagues ... id name credits ...

56 zoe 12 79 john 126

Separate columns vs duplicate columns
● Separate table mapping
       We can add attributes to the superclass easily 
by adding a column to the superclass table.
   Searching for the attributes of an object require  
 join operation.
● Duplicated columns
         Modifying the database schema is more 
 complex and error­pron.
    Individual objects are not fragment across the    
  number of tables, resulting in faster queries.
● Mapping concept (model transformation, refactoring,forward engineering,reverse 
● Optimizing object model design (reduce many associations, collapse objects into attributes).
● Transferring and Mapping associations to collections (one­to­one, one­to­many, many­to­
many, qualified associations with unidirectional and bidirectional capabilities).
● Transferring the association class into separate object and binary associations.
● Exception handling in java using try­throw­catch mechanism.

● Implementing a contract using ( checking precondition, checking postcondition, invariants ).
● Mapping classes to relational database tables ( map UML class to a table and attributes in 
● Realizing inheritance ( vertical mapping, horizontal mapping )
● Comparing realizing inheritance methods.
● Separate columns vs duplicate columns , separate column need join operation, duplicate 
columns error pron but faster.