SlideShare ist ein Scribd-Unternehmen logo
1 von 58
Lecture 09
The Behavioral Problem
Reading
 Fowler 3 Mapping to Relational Database
– The Behavioural Problem

 Fowler 12: Object-Relational Behavioral
Patterns
– Unit of work
– Identity Map
– Lazy Load
Agenda
 Error handling
 The Behavioral Problem
 Object-Relational Behavioral Patterns
– Unit of work
– Identity Map
– Lazy Load

 Object-Relational Mapping
Error Handling

Copyright © 2008 Ólafur Andri Ragnarsson
Error handling
 Important aspect of programming

– Programming the best case is usually easy
– Making programs robust is another thing

 Empty catch-blocks are usually not acceptable
– Can be worse since the error gets lost
– system.out.println is usually not practical

 How to handle exception

– Log the exception
– Create a new exception and throw
– Ignore and have upper layers handle the exception
Some guidelines
 If you cannot handle an exception, don’t catch it
 If you catch an exception, don’t eat it
 If you need to handle an exception
– Log with useful information
– Catch it where you can do something with it

 Use domain specific exception
– Removes dependences
– Example: Should SQLException be handled in the
web layer if there is duplicate row in the database?
Exception Handling
 Exceptions flow through layers

– Catch exception at the source and throw a domain specific
exception
– Upper layers will handle the error

 Example: Add User

– Table Data Gateway add method catches a duplicate
database exception
– Throw domain specific exception
– Each layer will ignore the exception, just pass it through
– Web layer decides to display message to user saying the
username chosen is already taken
Error Flow
Types of Exceptions
 Unchecked
– Can occur at any time
– For example
• OutOfMemoryError, NullPointerException

 Checked
– Part of declaration, must he handled or specifically
handed to the caller
public static String readFirstLine(String filename)
throwsIOException
{ ...
Unexpected Exceptions
 Problem with checked exceptions
–
–
–
–

Too much code – unnessary try-catch blocks
Hard-to-read code – difficult to see the real code
The real error can get lost
Dependencies

 Guidelines

– Use checked exception if caller must deal with the
problem, the exception has direct consequences to the
computation
– In layered systems, if the calling layer will not be able to do
anything, log and throw unchecked exception
– Layer controlling the flow will handle
Unchecked exceptions
Example
public class UserInserter extends SqlUpdate
{
...
public int insert(User user)
{
int rows = 0;
try {
rows = update(new Object[] {
user.getUsername(), user.getName(),
user.getEmail(), user.getPassword(), });
}
catch (DataIntegrityViolationException divex)
{
String msg = "User '" + user.getUsername() +
"' is already registered.";
log.info(msg);
throw new RuDuplicateDataException(msg, divex);
}
Example
catch (Throwable t)
{
String msg = "Unable to access Database: cause: " +
t.getMessage();
log.severe(msg);
throw new RuDataAccessException(msg, t);
}
return rows;
}
}
UserDataGateway
 Do not need to handle the exception
public class UserData extends RuData implements UserDataGateway
{
UserInserteruserInserter = ...
public void addUser(User user)
{
userInserter.insert(user);
}
...
}
public interface UserDataGateway extends RuDataGateway
{
User findUser(int id);
Collection findByName(String name);
void addUser(User user);
void updateUser(User user);
void deteleUser(int id);
}
QUIZ
Which of these statements is not true
A)
B)
✔ C)
D)

Checked exceptions must be always be handled by caller
In layered systems, each layer must handle exceptions
Unchecked exceptions are never handled
Checked exceptions require more coding
The Behavioral Problem
The Behavioral Problem
 Object-Relational Mapping

– How you relate tables to objects

 The Data Source Layer patterns are architectural
patterns – the focus on structure
–
–
–
–

Row Data Gateway,
Table Data Gateway,
Active Record, and
Data Mapper

 They simply tell you how to load and save objects to
tables
– What if you maintain these objects in-memory?
The Behavioral Problem
 How to get various object to load and save
themselves to the database
– With objects in memory, how can we keep track of
modified objects?
– What if we have two of the same object in memory
and both are changed?
– How can we maintain consistency and data integrity?
– What if you need object that is already in memory?
Keeping track of changed Objects
 Simple way is to have an object that keeps track
of other objects
– Unit of Work

 The idea is this
– When object is loaded it is registered as “clean” in the
UoW
– If modified, it is marked “dirty”
– When writing all objects back, just write the dirty ones
Keeping track of loaded Objects
 What if you need an object from the database –
is it already loaded? And changed?
– Identity Map

 The idea is this
– Keep all objects in a map and check get them from
the map
– If they are not in the map, load them from the
database
Loading Objects
 For rich data models, what about loading object
hierarchies?
– Do we need to load all linked objects?
– Lazy Load

 The idea is this
– We load part of the objects but maintain a placeholder
that we use when the rest of the object is needed
Unit of Work
Maintains a list of objects affected by a business
transaction and coordinates the writing out of
changes and the resolution of concurrency
problems
 Keeps track of objects that are moved in and out
of the database
– What has changed?
Unit of Work
 How It Works

– Unit of Work is an object that tracks all changes to the
database
– As soon as something affects the database, tell the Unit of
Work
– The Unit of Work must know the state of objects
• Upon committing the Unit of Work decides what to do
• Application programmers don’t have know what to write to the
database

 Two methods

– Caller registration
– Object registration
Unit of Work
 Caller Registration
– User of the object has to remember to register the
object with the Unit of Work for changes
Unit of Work
 Object Registration
– The object must register itself with the Unit of work
Unit of Work
 When to Use It
– When you have in-memory objects you need to
synchronize with the database
– When you have many updates to objects and you
want to avoid unneeded calls to the database to save
the object

 Benefits
– Keeps the state of object in one place
Identity Map
Ensures that each object gets loaded only once by
keeping every loaded object in a map. Looks up
objects using the map when referring to them
 Keeps a record of all the objects that have been
read
Identity Map
 How It Works

– Contains a map of all loaded objects
– Provides method to get the objects

 Choice of Key

– Usually the primary key

 Explicit or Generic

– Explicit Identity Maps have method of the type of the
object
• Person findPerson (1)

– Generic Identity Maps have generic objects and keys
• Object find(“person”, 1)
Identity Map
 How Many

– One map per class or per session
– Session maps works for database-unique keys
– For multiple maps, maintain one per class or per table

 Where to put them

– Identity maps need to be somewhere
– Can be part of Unit of work
– Can be in a Registry

 Identity Maps can be used as cache
– Works well if objects are read-only
Identity Map
 When to Use It
– When you need to load objects to memory and you
don’t want them duplicated
– Main benefit of Identity Map is avoiding problems
when object is updated in-memory
– For immutable object, such as value object, Identity
Map is not needed – object may be duplicated

 Performance
– When you need caching of objects for performance
Lazy Load
An object that doesn’t contain all of the data you
need but knows how to get it
 Load only the data that is needed
– Load the rest when it is needed
Lazy Load
 How It Works
– Object can contain other objects and associations
– Loading all the data might be too much
– Lazy Load delays loading until the objects are
needed

 Four ways to implement Lazy Load
–
–
–
–

Lazy Initialization
Virtual Proxy
Value Holder
A ghost
Lazy Load
 Lazy Initialization
– Uses a special marker value (usually null) to indicate
a field isn't loaded
– Every access to the field checks the field for the
marker value and if unloaded, loads it
Class Supplier...
public List getProducts() {
if (products == null)
products = Product.findSupplier(getId());
return products;
}
Lazy Load
 Virtual Proxy
– An object with the same interface as the real object
– The first time one of its methods are called it loads the
real the object and then delegates.
Class VirtualList...
private List source;
private VirtualListLoader loader;
public VirtualList(VirtualListLoader loader) {
this.loader = loader;
}
private List getSource() {
if(source == null) source = loader.load();
return source();
}
public int size() {
return getSource().size();
}
Lazy Load
 Value Holder
– An object with a getValue method
– Clients call getValue to get the real object, the first
call triggers the load
Class SupplierVH...
private ValueHolder products;
public List getProducts() {
return (List)products.getValue();
}
Class ValueHolder…
private Object Value;
...
public Object getValue() {
if (value==null) value = loader.load();
return value;
}
Lazy Load
 A ghost
– The real object without any data
– The first time you call a method the ghost loads the
full data into its fields
class Domain Object
protected void Load() {
if(IsGhost())
DataSource.load(this);
}

Class Employee...
public String Name {
get {
Load();
return _name;
}
set {
Load();
_name = value;
}
}
String _name;
Lazy Load
 When to Use It
– When you have complex objects with associations
with other objects
– Need to decide how much to get on a hit and how
many hits we want
– Rule might be to bring in everything you need in one
call
• The overhead of taking extra fields in the table is not that
high

– The best time to use Lazy Load is when it involves an
extra call and the data you’re calling isn’t used when
the main object is used
QUIZ
We are writing a business application which is using fairly large
data set. We only need to update few objects. Writing them all
back to database is too expensive. What pattern can we use?
A)
B)
✔ C)
D)

Lazy Load
Identity Map
Unit of Work
Data Mapper
Object Relational Mapping
Object Relational Mapping (ORM)
 Use a mapping layer to map between objects
and tables
– Mapping a data representation from an object model
to a relational data model with a SQL-based schema

 Mapping requires
metadata
– XML

 Authoring and
maintaining
metadata is less work than maintaining SQL
Advantages of ORM
 Can radically reduce the amount of code you
need to write
– 30% compared to JDBC for server side application

 More Productivity
 Applications are easier to maintain
 Fosters thinking about an OO domain model
Disadvantages of ORM
 Some loss of control over the persistence
process
 May be more difficult to tune queries
 Performance characteristics of the tool may
affect your application’s performance
When to use ORM?
 Well-suited to ORM
– Read-modify-write lifecycle
– Little requirement for stored procedures

 Poorly suited to ORM
– “Window on data” application
– Significant use of stored procedures
– Write centric apps, where data is seldom read
When to use ORM?
 Typical server-side applications are fairly well
suited for ORM
– 90%-95% of applications
– But there are always some special cases
– Mix and match as needed
Hibernate
Hibernate
 Object/relational mapping tool
– A persistence service that stores Java objects in
relational databases
– Provides an object oriented view of existing relational
data

 Uses reflection and XML mapping files to
persist POJOs
– No changes to business domain objects
– The goal is to relieve the developer from a significant
amount of common data persistence-related
programming tasks
Architecture
 High-level architecture

Properties
file define
data access

Mapping
definition
maps classes
to tables
Architecture
Database Properties
 File

– hibernate.properties

hibernate.connection.username=andri
hibernate.connection.password=abc123
hibernate.connection.url=jdbc:jtds:sqlserver://honn.ru.is:1433
hibernate.connection.driver_class=net.sourceforge.jtds.jdbc.Driver

 Contains information to access the database
– Username and password
– URL
– Database driver

 Hibernate will automatically read the file from the
classpath
Mapping File
 File
– hibernate-mapping
– In the same package as Nemandi class
<hibernate-mapping>
<class name="org.ru.honn.domain.Nemandi" table="NEMENDUR">

<id name="kennitala" column="kennitala" type="string">
</id>
<property name="nafn" column="nafn" type="string"
length="64" not-null="false"/>
<property name="netfang" column="netfang" type="string"
length="64" not-null="false"/>
<property name="hopur" column="hopur" type="string"
length="32" not-null="false" />
</class>
</hibernate-mapping>
Using Hibernate
 Usually an application will
– Create a single Configuration
– Build a single instance of SessionFactory
– Then instantiate Session objects
Configuration cfg = new Configuration();
cfg.addClass(theClass);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Using Hibernate
 Configuration
– Allows the application to specify properties and
mapping documents to be used when creating a
SessionFactor

 SessionFactory
– Factory class to create Session objects

 Session
– Interface that represents a transaction
– The main function is to offer create, read and delete
operations for instances of mapped entity classes
Example
 NemandiGateway
public interface NemandiGateway
{
public Nemandi findNemandi(String kennitala);
public Collection getNemendur();
public void addNemandi(Nemandi nemandi);
}
Example
 NemandiData
– Constructor creates the configuration and the factory
– Variable factory is used when a Session is needed
public class NemandiData implements NemandiGateway
{
SessionFactory factory = null;
public NemandiData()
{
Configuration cfg = new Configuration();
cfg.addClass(Nemandi.class);
factory = cfg.buildSessionFactory();
}
Example
 NemandiData
– findNemandi
public Nemandi findNemandi(String kennitala)
{
Session session = factory.openSession();
Nemandi nem = (Nemandi)session.get(Nemandi.class, kennitala);
session.close();
return nem;
}
Example
 NemandiData
– getNemendur
public Collection getNemendur()
{
Session session = factory.openSession();
List l = session.createQuery(
"SELECT n FROM is.ru.honn.domain.Nemandi AS n").list();
session.close();
return l;
}

– Uses the Hibernate Query Language, HQL
Example
 NemandiData
– addNemandi
public void addNemandi(Nemandi nemandi)
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
session.save(nemandi);
tx.commit();
session.close();
}
Summary
 The Behavioral Problem
– When objects are used

 Object-Relational Behavioral Patterns
– Unit of work
– Identity Map
– Lazy Load

 Object-Relational Mapping

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013Roger Barnes
 
Easy Dataweave transformations - Ashutosh
Easy Dataweave transformations - AshutoshEasy Dataweave transformations - Ashutosh
Easy Dataweave transformations - AshutoshStrawhatLuffy11
 
Kelis king - introduction to software design
Kelis king -  introduction to software designKelis king -  introduction to software design
Kelis king - introduction to software designKelisKing
 
Introduction of Oracle
Introduction of Oracle Introduction of Oracle
Introduction of Oracle Salman Memon
 
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)Michael Rys
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldevllangit
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersllangit
 
Software Development: Beyond Training wheels
Software Development: Beyond Training wheelsSoftware Development: Beyond Training wheels
Software Development: Beyond Training wheelsNaveenkumar Muguda
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
Interactive Questions and Answers - London Information Retrieval Meetup
Interactive Questions and Answers - London Information Retrieval MeetupInteractive Questions and Answers - London Information Retrieval Meetup
Interactive Questions and Answers - London Information Retrieval MeetupSease
 
Hand Coding ETL Scenarios and Challenges
Hand Coding ETL Scenarios and ChallengesHand Coding ETL Scenarios and Challenges
Hand Coding ETL Scenarios and Challengesmark madsen
 
Architectural Anti Patterns - Notes on Data Distribution and Handling Failures
Architectural Anti Patterns - Notes on Data Distribution and Handling FailuresArchitectural Anti Patterns - Notes on Data Distribution and Handling Failures
Architectural Anti Patterns - Notes on Data Distribution and Handling FailuresGleicon Moraes
 
AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)avocadodb
 

Was ist angesagt? (18)

Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013
 
Datastage Introduction To Data Warehousing
Datastage Introduction To Data Warehousing Datastage Introduction To Data Warehousing
Datastage Introduction To Data Warehousing
 
Oracle
OracleOracle
Oracle
 
Dataweave nagarjuna
Dataweave nagarjunaDataweave nagarjuna
Dataweave nagarjuna
 
Easy Dataweave transformations - Ashutosh
Easy Dataweave transformations - AshutoshEasy Dataweave transformations - Ashutosh
Easy Dataweave transformations - Ashutosh
 
Kelis king - introduction to software design
Kelis king -  introduction to software designKelis king -  introduction to software design
Kelis king - introduction to software design
 
Introduction of Oracle
Introduction of Oracle Introduction of Oracle
Introduction of Oracle
 
The Smartpath Information Systems | BASIC RDBMS CONCEPTS
The Smartpath Information Systems | BASIC RDBMS CONCEPTSThe Smartpath Information Systems | BASIC RDBMS CONCEPTS
The Smartpath Information Systems | BASIC RDBMS CONCEPTS
 
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldev
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
Software Development: Beyond Training wheels
Software Development: Beyond Training wheelsSoftware Development: Beyond Training wheels
Software Development: Beyond Training wheels
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
Interactive Questions and Answers - London Information Retrieval Meetup
Interactive Questions and Answers - London Information Retrieval MeetupInteractive Questions and Answers - London Information Retrieval Meetup
Interactive Questions and Answers - London Information Retrieval Meetup
 
Ado.net
Ado.netAdo.net
Ado.net
 
Hand Coding ETL Scenarios and Challenges
Hand Coding ETL Scenarios and ChallengesHand Coding ETL Scenarios and Challenges
Hand Coding ETL Scenarios and Challenges
 
Architectural Anti Patterns - Notes on Data Distribution and Handling Failures
Architectural Anti Patterns - Notes on Data Distribution and Handling FailuresArchitectural Anti Patterns - Notes on Data Distribution and Handling Failures
Architectural Anti Patterns - Notes on Data Distribution and Handling Failures
 
AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)AvocadoDB query language (DRAFT!)
AvocadoDB query language (DRAFT!)
 

Andere mochten auch

A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)
A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)
A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)Elena Planas
 
USC Creative Media & Behavioral Health Center
USC Creative Media & Behavioral Health CenterUSC Creative Media & Behavioral Health Center
USC Creative Media & Behavioral Health CenterMarientina Gotsis
 
Special behavioral problems of Student
Special behavioral problems of StudentSpecial behavioral problems of Student
Special behavioral problems of StudentMi L
 
Problem formulation
Problem formulationProblem formulation
Problem formulationH9460730008
 
Research Paper and the Theoretical Framework
Research Paper and the Theoretical FrameworkResearch Paper and the Theoretical Framework
Research Paper and the Theoretical FrameworkDAPHNIE MONTEVERDE
 
Research Methodology & Thesis Topic Proposals
Research Methodology & Thesis Topic ProposalsResearch Methodology & Thesis Topic Proposals
Research Methodology & Thesis Topic Proposalsetaurisani
 
Research methodology for behavioral research
Research methodology for behavioral researchResearch methodology for behavioral research
Research methodology for behavioral researchrip1971
 
Spark for Behavioral Analytics Research: Spark Summit East talk by John W u
Spark for Behavioral Analytics Research: Spark Summit East talk by John W uSpark for Behavioral Analytics Research: Spark Summit East talk by John W u
Spark for Behavioral Analytics Research: Spark Summit East talk by John W uSpark Summit
 

Andere mochten auch (11)

A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)
A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)
A Framework for Verifying UML Behavioral Models (CAiSE Doctoral Consortium 2009)
 
USC Creative Media & Behavioral Health Center
USC Creative Media & Behavioral Health CenterUSC Creative Media & Behavioral Health Center
USC Creative Media & Behavioral Health Center
 
Special behavioral problems of Student
Special behavioral problems of StudentSpecial behavioral problems of Student
Special behavioral problems of Student
 
Developmental Designs (CPR)
Developmental Designs (CPR)Developmental Designs (CPR)
Developmental Designs (CPR)
 
Behavioral problems
Behavioral problemsBehavioral problems
Behavioral problems
 
Problem formulation
Problem formulationProblem formulation
Problem formulation
 
Research Paper and the Theoretical Framework
Research Paper and the Theoretical FrameworkResearch Paper and the Theoretical Framework
Research Paper and the Theoretical Framework
 
Research Methodology & Thesis Topic Proposals
Research Methodology & Thesis Topic ProposalsResearch Methodology & Thesis Topic Proposals
Research Methodology & Thesis Topic Proposals
 
Research methodology for behavioral research
Research methodology for behavioral researchResearch methodology for behavioral research
Research methodology for behavioral research
 
Spark for Behavioral Analytics Research: Spark Summit East talk by John W u
Spark for Behavioral Analytics Research: Spark Summit East talk by John W uSpark for Behavioral Analytics Research: Spark Summit East talk by John W u
Spark for Behavioral Analytics Research: Spark Summit East talk by John W u
 
Chapter 6-THEORETICAL & CONCEPTUAL FRAMEWORK
Chapter 6-THEORETICAL & CONCEPTUAL FRAMEWORKChapter 6-THEORETICAL & CONCEPTUAL FRAMEWORK
Chapter 6-THEORETICAL & CONCEPTUAL FRAMEWORK
 

Ähnlich wie L09 The Behavioral Problem

02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Stacks
StacksStacks
StacksAcad
 
Parallel programming
Parallel programmingParallel programming
Parallel programmingSwain Loda
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iTaymoor Nazmy
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptxMugiiiReee
 
Programming concepts and data management
Programming concepts and data management Programming concepts and data management
Programming concepts and data management Wulax37
 
Data Structure Notes unit 1.docx
Data Structure Notes unit 1.docxData Structure Notes unit 1.docx
Data Structure Notes unit 1.docxkp370932
 
L1-Introduction to OOPs concepts.pdf
L1-Introduction to OOPs concepts.pdfL1-Introduction to OOPs concepts.pdf
L1-Introduction to OOPs concepts.pdfBhanuJatinSingh
 
ItemMirror, XML & The Promise of Information Integration
ItemMirror, XML & The Promise of Information IntegrationItemMirror, XML & The Promise of Information Integration
ItemMirror, XML & The Promise of Information Integrationkeepingfoundthingsfound
 
Doctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkDoctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkIllia Antypenko
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 

Ähnlich wie L09 The Behavioral Problem (20)

L06 Using Design Patterns
L06 Using Design PatternsL06 Using Design Patterns
L06 Using Design Patterns
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
 
Data Structures
Data StructuresData Structures
Data Structures
 
Stacks
StacksStacks
Stacks
 
Parallel programming
Parallel programmingParallel programming
Parallel programming
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notes
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
 
L15 Data Source Layer
L15 Data Source LayerL15 Data Source Layer
L15 Data Source Layer
 
Sap business objects interview questions
Sap business objects interview questionsSap business objects interview questions
Sap business objects interview questions
 
Programming concepts and data management
Programming concepts and data management Programming concepts and data management
Programming concepts and data management
 
CoreData
CoreDataCoreData
CoreData
 
Data Structure Notes unit 1.docx
Data Structure Notes unit 1.docxData Structure Notes unit 1.docx
Data Structure Notes unit 1.docx
 
L1-Introduction to OOPs concepts.pdf
L1-Introduction to OOPs concepts.pdfL1-Introduction to OOPs concepts.pdf
L1-Introduction to OOPs concepts.pdf
 
Oop
OopOop
Oop
 
ItemMirror, XML & The Promise of Information Integration
ItemMirror, XML & The Promise of Information IntegrationItemMirror, XML & The Promise of Information Integration
ItemMirror, XML & The Promise of Information Integration
 
Doctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkDoctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWork
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 

Mehr von Ólafur Andri Ragnarsson

New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionÓlafur Andri Ragnarsson
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine Ólafur Andri Ragnarsson
 

Mehr von Ólafur Andri Ragnarsson (20)

Nýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfaraNýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfara
 
Nýjast tækni og framtíðin
Nýjast tækni og framtíðinNýjast tækni og framtíðin
Nýjast tækni og framtíðin
 
New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course Introduction
 
L01 Introduction
L01 IntroductionL01 Introduction
L01 Introduction
 
L23 Robotics and Drones
L23 Robotics and Drones L23 Robotics and Drones
L23 Robotics and Drones
 
L22 Augmented and Virtual Reality
L22 Augmented and Virtual RealityL22 Augmented and Virtual Reality
L22 Augmented and Virtual Reality
 
L20 Personalised World
L20 Personalised WorldL20 Personalised World
L20 Personalised World
 
L19 Network Platforms
L19 Network PlatformsL19 Network Platforms
L19 Network Platforms
 
L18 Big Data and Analytics
L18 Big Data and AnalyticsL18 Big Data and Analytics
L18 Big Data and Analytics
 
L17 Algorithms and AI
L17 Algorithms and AIL17 Algorithms and AI
L17 Algorithms and AI
 
L16 Internet of Things
L16 Internet of ThingsL16 Internet of Things
L16 Internet of Things
 
L14 From the Internet to Blockchain
L14 From the Internet to BlockchainL14 From the Internet to Blockchain
L14 From the Internet to Blockchain
 
L14 The Mobile Revolution
L14 The Mobile RevolutionL14 The Mobile Revolution
L14 The Mobile Revolution
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine
 
L12 digital transformation
L12 digital transformationL12 digital transformation
L12 digital transformation
 
L10 The Innovator's Dilemma
L10 The Innovator's DilemmaL10 The Innovator's Dilemma
L10 The Innovator's Dilemma
 
L09 Disruptive Technology
L09 Disruptive TechnologyL09 Disruptive Technology
L09 Disruptive Technology
 
L09 Technological Revolutions
L09 Technological RevolutionsL09 Technological Revolutions
L09 Technological Revolutions
 
L07 Becoming Invisible
L07 Becoming InvisibleL07 Becoming Invisible
L07 Becoming Invisible
 
L06 Diffusion of Innovation
L06 Diffusion of InnovationL06 Diffusion of Innovation
L06 Diffusion of Innovation
 

Kürzlich hochgeladen

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

L09 The Behavioral Problem

  • 2. Reading  Fowler 3 Mapping to Relational Database – The Behavioural Problem  Fowler 12: Object-Relational Behavioral Patterns – Unit of work – Identity Map – Lazy Load
  • 3. Agenda  Error handling  The Behavioral Problem  Object-Relational Behavioral Patterns – Unit of work – Identity Map – Lazy Load  Object-Relational Mapping
  • 4. Error Handling Copyright © 2008 Ólafur Andri Ragnarsson
  • 5. Error handling  Important aspect of programming – Programming the best case is usually easy – Making programs robust is another thing  Empty catch-blocks are usually not acceptable – Can be worse since the error gets lost – system.out.println is usually not practical  How to handle exception – Log the exception – Create a new exception and throw – Ignore and have upper layers handle the exception
  • 6. Some guidelines  If you cannot handle an exception, don’t catch it  If you catch an exception, don’t eat it  If you need to handle an exception – Log with useful information – Catch it where you can do something with it  Use domain specific exception – Removes dependences – Example: Should SQLException be handled in the web layer if there is duplicate row in the database?
  • 7. Exception Handling  Exceptions flow through layers – Catch exception at the source and throw a domain specific exception – Upper layers will handle the error  Example: Add User – Table Data Gateway add method catches a duplicate database exception – Throw domain specific exception – Each layer will ignore the exception, just pass it through – Web layer decides to display message to user saying the username chosen is already taken
  • 9. Types of Exceptions  Unchecked – Can occur at any time – For example • OutOfMemoryError, NullPointerException  Checked – Part of declaration, must he handled or specifically handed to the caller public static String readFirstLine(String filename) throwsIOException { ...
  • 10. Unexpected Exceptions  Problem with checked exceptions – – – – Too much code – unnessary try-catch blocks Hard-to-read code – difficult to see the real code The real error can get lost Dependencies  Guidelines – Use checked exception if caller must deal with the problem, the exception has direct consequences to the computation – In layered systems, if the calling layer will not be able to do anything, log and throw unchecked exception – Layer controlling the flow will handle
  • 12. Example public class UserInserter extends SqlUpdate { ... public int insert(User user) { int rows = 0; try { rows = update(new Object[] { user.getUsername(), user.getName(), user.getEmail(), user.getPassword(), }); } catch (DataIntegrityViolationException divex) { String msg = "User '" + user.getUsername() + "' is already registered."; log.info(msg); throw new RuDuplicateDataException(msg, divex); }
  • 13. Example catch (Throwable t) { String msg = "Unable to access Database: cause: " + t.getMessage(); log.severe(msg); throw new RuDataAccessException(msg, t); } return rows; } }
  • 14. UserDataGateway  Do not need to handle the exception public class UserData extends RuData implements UserDataGateway { UserInserteruserInserter = ... public void addUser(User user) { userInserter.insert(user); } ... } public interface UserDataGateway extends RuDataGateway { User findUser(int id); Collection findByName(String name); void addUser(User user); void updateUser(User user); void deteleUser(int id); }
  • 15. QUIZ Which of these statements is not true A) B) ✔ C) D) Checked exceptions must be always be handled by caller In layered systems, each layer must handle exceptions Unchecked exceptions are never handled Checked exceptions require more coding
  • 17. The Behavioral Problem  Object-Relational Mapping – How you relate tables to objects  The Data Source Layer patterns are architectural patterns – the focus on structure – – – – Row Data Gateway, Table Data Gateway, Active Record, and Data Mapper  They simply tell you how to load and save objects to tables – What if you maintain these objects in-memory?
  • 18. The Behavioral Problem  How to get various object to load and save themselves to the database – With objects in memory, how can we keep track of modified objects? – What if we have two of the same object in memory and both are changed? – How can we maintain consistency and data integrity? – What if you need object that is already in memory?
  • 19. Keeping track of changed Objects  Simple way is to have an object that keeps track of other objects – Unit of Work  The idea is this – When object is loaded it is registered as “clean” in the UoW – If modified, it is marked “dirty” – When writing all objects back, just write the dirty ones
  • 20. Keeping track of loaded Objects  What if you need an object from the database – is it already loaded? And changed? – Identity Map  The idea is this – Keep all objects in a map and check get them from the map – If they are not in the map, load them from the database
  • 21. Loading Objects  For rich data models, what about loading object hierarchies? – Do we need to load all linked objects? – Lazy Load  The idea is this – We load part of the objects but maintain a placeholder that we use when the rest of the object is needed
  • 22. Unit of Work Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems  Keeps track of objects that are moved in and out of the database – What has changed?
  • 23. Unit of Work  How It Works – Unit of Work is an object that tracks all changes to the database – As soon as something affects the database, tell the Unit of Work – The Unit of Work must know the state of objects • Upon committing the Unit of Work decides what to do • Application programmers don’t have know what to write to the database  Two methods – Caller registration – Object registration
  • 24. Unit of Work  Caller Registration – User of the object has to remember to register the object with the Unit of Work for changes
  • 25. Unit of Work  Object Registration – The object must register itself with the Unit of work
  • 26. Unit of Work  When to Use It – When you have in-memory objects you need to synchronize with the database – When you have many updates to objects and you want to avoid unneeded calls to the database to save the object  Benefits – Keeps the state of object in one place
  • 27. Identity Map Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them  Keeps a record of all the objects that have been read
  • 28. Identity Map  How It Works – Contains a map of all loaded objects – Provides method to get the objects  Choice of Key – Usually the primary key  Explicit or Generic – Explicit Identity Maps have method of the type of the object • Person findPerson (1) – Generic Identity Maps have generic objects and keys • Object find(“person”, 1)
  • 29. Identity Map  How Many – One map per class or per session – Session maps works for database-unique keys – For multiple maps, maintain one per class or per table  Where to put them – Identity maps need to be somewhere – Can be part of Unit of work – Can be in a Registry  Identity Maps can be used as cache – Works well if objects are read-only
  • 30. Identity Map  When to Use It – When you need to load objects to memory and you don’t want them duplicated – Main benefit of Identity Map is avoiding problems when object is updated in-memory – For immutable object, such as value object, Identity Map is not needed – object may be duplicated  Performance – When you need caching of objects for performance
  • 31. Lazy Load An object that doesn’t contain all of the data you need but knows how to get it  Load only the data that is needed – Load the rest when it is needed
  • 32. Lazy Load  How It Works – Object can contain other objects and associations – Loading all the data might be too much – Lazy Load delays loading until the objects are needed  Four ways to implement Lazy Load – – – – Lazy Initialization Virtual Proxy Value Holder A ghost
  • 33. Lazy Load  Lazy Initialization – Uses a special marker value (usually null) to indicate a field isn't loaded – Every access to the field checks the field for the marker value and if unloaded, loads it Class Supplier... public List getProducts() { if (products == null) products = Product.findSupplier(getId()); return products; }
  • 34. Lazy Load  Virtual Proxy – An object with the same interface as the real object – The first time one of its methods are called it loads the real the object and then delegates. Class VirtualList... private List source; private VirtualListLoader loader; public VirtualList(VirtualListLoader loader) { this.loader = loader; } private List getSource() { if(source == null) source = loader.load(); return source(); } public int size() { return getSource().size(); }
  • 35. Lazy Load  Value Holder – An object with a getValue method – Clients call getValue to get the real object, the first call triggers the load Class SupplierVH... private ValueHolder products; public List getProducts() { return (List)products.getValue(); } Class ValueHolder… private Object Value; ... public Object getValue() { if (value==null) value = loader.load(); return value; }
  • 36. Lazy Load  A ghost – The real object without any data – The first time you call a method the ghost loads the full data into its fields class Domain Object protected void Load() { if(IsGhost()) DataSource.load(this); } Class Employee... public String Name { get { Load(); return _name; } set { Load(); _name = value; } } String _name;
  • 37. Lazy Load  When to Use It – When you have complex objects with associations with other objects – Need to decide how much to get on a hit and how many hits we want – Rule might be to bring in everything you need in one call • The overhead of taking extra fields in the table is not that high – The best time to use Lazy Load is when it involves an extra call and the data you’re calling isn’t used when the main object is used
  • 38. QUIZ We are writing a business application which is using fairly large data set. We only need to update few objects. Writing them all back to database is too expensive. What pattern can we use? A) B) ✔ C) D) Lazy Load Identity Map Unit of Work Data Mapper
  • 40. Object Relational Mapping (ORM)  Use a mapping layer to map between objects and tables – Mapping a data representation from an object model to a relational data model with a SQL-based schema  Mapping requires metadata – XML  Authoring and maintaining metadata is less work than maintaining SQL
  • 41. Advantages of ORM  Can radically reduce the amount of code you need to write – 30% compared to JDBC for server side application  More Productivity  Applications are easier to maintain  Fosters thinking about an OO domain model
  • 42. Disadvantages of ORM  Some loss of control over the persistence process  May be more difficult to tune queries  Performance characteristics of the tool may affect your application’s performance
  • 43. When to use ORM?  Well-suited to ORM – Read-modify-write lifecycle – Little requirement for stored procedures  Poorly suited to ORM – “Window on data” application – Significant use of stored procedures – Write centric apps, where data is seldom read
  • 44. When to use ORM?  Typical server-side applications are fairly well suited for ORM – 90%-95% of applications – But there are always some special cases – Mix and match as needed
  • 46. Hibernate  Object/relational mapping tool – A persistence service that stores Java objects in relational databases – Provides an object oriented view of existing relational data  Uses reflection and XML mapping files to persist POJOs – No changes to business domain objects – The goal is to relieve the developer from a significant amount of common data persistence-related programming tasks
  • 47. Architecture  High-level architecture Properties file define data access Mapping definition maps classes to tables
  • 49. Database Properties  File – hibernate.properties hibernate.connection.username=andri hibernate.connection.password=abc123 hibernate.connection.url=jdbc:jtds:sqlserver://honn.ru.is:1433 hibernate.connection.driver_class=net.sourceforge.jtds.jdbc.Driver  Contains information to access the database – Username and password – URL – Database driver  Hibernate will automatically read the file from the classpath
  • 50. Mapping File  File – hibernate-mapping – In the same package as Nemandi class <hibernate-mapping> <class name="org.ru.honn.domain.Nemandi" table="NEMENDUR"> <id name="kennitala" column="kennitala" type="string"> </id> <property name="nafn" column="nafn" type="string" length="64" not-null="false"/> <property name="netfang" column="netfang" type="string" length="64" not-null="false"/> <property name="hopur" column="hopur" type="string" length="32" not-null="false" /> </class> </hibernate-mapping>
  • 51. Using Hibernate  Usually an application will – Create a single Configuration – Build a single instance of SessionFactory – Then instantiate Session objects Configuration cfg = new Configuration(); cfg.addClass(theClass); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession();
  • 52. Using Hibernate  Configuration – Allows the application to specify properties and mapping documents to be used when creating a SessionFactor  SessionFactory – Factory class to create Session objects  Session – Interface that represents a transaction – The main function is to offer create, read and delete operations for instances of mapped entity classes
  • 53. Example  NemandiGateway public interface NemandiGateway { public Nemandi findNemandi(String kennitala); public Collection getNemendur(); public void addNemandi(Nemandi nemandi); }
  • 54. Example  NemandiData – Constructor creates the configuration and the factory – Variable factory is used when a Session is needed public class NemandiData implements NemandiGateway { SessionFactory factory = null; public NemandiData() { Configuration cfg = new Configuration(); cfg.addClass(Nemandi.class); factory = cfg.buildSessionFactory(); }
  • 55. Example  NemandiData – findNemandi public Nemandi findNemandi(String kennitala) { Session session = factory.openSession(); Nemandi nem = (Nemandi)session.get(Nemandi.class, kennitala); session.close(); return nem; }
  • 56. Example  NemandiData – getNemendur public Collection getNemendur() { Session session = factory.openSession(); List l = session.createQuery( "SELECT n FROM is.ru.honn.domain.Nemandi AS n").list(); session.close(); return l; } – Uses the Hibernate Query Language, HQL
  • 57. Example  NemandiData – addNemandi public void addNemandi(Nemandi nemandi) { Session session = factory.openSession(); Transaction tx = session.beginTransaction(); session.save(nemandi); tx.commit(); session.close(); }
  • 58. Summary  The Behavioral Problem – When objects are used  Object-Relational Behavioral Patterns – Unit of work – Identity Map – Lazy Load  Object-Relational Mapping