MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO...

30
MTAT.03.229 Enterprise System Integration Lecture 2: Domain model and data access layer Luciano García-Bañuelos University of Tartu

Transcript of MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO...

Page 1: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

MTAT.03.229Enterprise System IntegrationLecture 2: Domain model and data access layerLucianoGarcía-BañuelosUnivers i tyof Tartu

Page 2: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

TheAnatomyofanEnterpriseSystem

1

Enterprisesoftw

are Presentation

Applicationlogic

Dataaccess

Applicationlayers

• Usersinteractwiththesystemthroughapresentationlayer(akauserinterface orUI)

• Theapplicationlogic (akabusiness logic)determineswhatthesystemactuallydoes:◦ Enforcesbusinessrules◦ Coordinatesbusinessprocesses

• Thedataaccesslayer facilitatestheaccesstopersistentdatamanipulatedbytheapplicationlogic.◦ Includesaccesstodatabases,searchengines,documentmanagersand/orafilesystem.

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS

Page 3: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Hexagonalarchitecture

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 2

Application

Domain model

RESTadapter

SOAPadapter

Mem

JPAadapter

MongoDBadapter

Hash mapadapter

Messagingadapter Messaging

adapterEMail

adapter

Web UIadapter

• Allowsmanydisparateclientstointeractwiththesystem:◦ The DomainmodelisonlyaccessibleviaaninternalApplicationAPI(innerhexagon)

◦ Needanewclient(withdifferent integrationrequirements)? JustaddanAdapter

◦ Usealsoadapterstointegratewithexternalapplicationsandinfrastructureservices

Page 4: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Domain-drivendesign(DDD)• Domain-drivendesign(DDD)isanapproachtodevelopingsoftwarefor complexneeds bydeeplyconnectingtheimplementationtoanevolvingmodelofthecorebusinessconcepts.

• Itspremisesare:◦ A developmentprojectmustprimarilyfocusinthecoredomainanddomainlogic

◦ Themodeliscentraltoanycomplexdesign◦ Thedevelopmentreliesoncreativecollaborationbetween technicalanddomainexperts toiterativelycuteverclosertotheconceptualheartoftheproblem

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 3

Page 5: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

TheFrameworkofDDD• Ubiquitouslanguage• Strategicdesign◦ BoundedContext◦ ContextMaps◦ Patterns:Sharedkernel,Anti-corruptionlayer,etc.

• Tacticdesign◦ Structuralpatterns:Entities,ValueObjectsandAggregates◦ Lifecyclepatterns:RepositoriesandFactories◦ Behaviorpatterns:Services,Domainevents,Eventsourcing(CQRS)◦ Stylepatterns:Modules,IntentionRevealingInterfaces,Specifications

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 4

Page 6: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Ubiquitous language

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 5

Sowhenwechangethecustomsclearancepoint,weneedtoredothewholeroutingplan

Right.We’lldeletealltherowsintheshipmenttablewiththecargoid.Then,we’llpasstheorigin,destinationandnewclearance

pointintotheRoutingservice,anditwillrepopulatethetable.Delete therows?OK,

whatever.Anyway,ifwedidn’thaveacustomsclearancepointatall

before,we’llhavetodothesamething.

Alanguagestructuredaroundtheapplication domain• Understoodbydomainexpertsandsoftwaredevelopment team

• Essentialincommunicatinginsightsfromthedomainthatmustbetransferred intothemodel

Page 7: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Strategicdesign• Inordertotacklecomplexity, thedomainisdecomposed insubdomains, usuallybasedonBusinesscapabilities◦ Identifythecoresubdomainandothersupportingsubdomains◦ Characterizetheofrelationshipsbetweensubdomains

• Theusageoftheubiquitous languageusedinthecoredomaindelimitsa bounded context◦ Usetheubiquitouslanguageintheprocessofmodelingthedomain◦ Strivetokeeptheconsistencyofthedomainmodelwiththecode◦ Infact,thecodeitselfisanotherrepresentationofthemodel

• WeneedtoidentifyanddescribethenatureoftherelationshipsbetweenboundedcontextsbymeansofContextMaps◦ Teamsworkingindifferentcontextboundsshouldtakecare(oratleastawareof)potential interdependencies

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 6

Page 8: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Rentit’s domain

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 7

Plant catalogand purchase

orders

Maintenance plan

Plant reservation

Invoicing

Plant transportation

Domain

Maintenance

Reservations

Transportation

Invoicing

Sales(core)

Sub-domain

BoundedContext

Page 9: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Exercise:Rentit• Sales◦ Queryingtheplantcatalog◦ Creatingapurchaseorder◦ Processingofapurchaseorder◦ Planttransportation◦ Invoicing

• Maintenance◦ Creationofyearlymaintenanceplan◦ Schedulingofmaintenancetasks

• Reservations◦ Howtocoordinaterentalandmaintenance(implicit)

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 8

Page 10: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

QueryingtheplantcatalogCustomers query Rentit’s plant catalog. For each plant, the plant catalogprovides a name, a description, and a daily rental price. Each entry in theplant catalog is referred to as plant inventory entry.There might be multiple plants for the same entry, each one having adifferent serial number. An actual plant is referred to as a plantinventory item.

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 9

Page 11: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

CreatingaPurchaseOrderA customer can check a plant's availability for a period of time. If theplant is available, he/she can create a Purchase Order with the followinginformation: customer’s company, contact person (e.g. name, email),construction site’s address, plant inventory entry’s identifier, the startand end dates of the rental period.

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 10

Page 12: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

ProcessingaPurchaseOrderA PO is initially considered ascreated. A clerk checks thecustomer’s credit status withthe department of finances,and the plant's availability. Ifeverything is OK, the clerknotifies the customer thatthe PO has been acceptedand updates the cost of thePO. Otherwise, the clerknotifies the rejection of thePO with an explanatory note.

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 11

Page 13: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Theoverallpicture

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 12

0..1

maintPlan

reservation1

0..1

rental

reservation0..1

1 plantreservation

1

1plant

Page 14: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

TacticDesign

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 13

Modeldrivendesign

ServicesEntities

Valueobjects

Modules

Repositories

Aggregates

Factories

accesswithmaintain

integritywithactasrootofencapsulate

withencapsulate

with

encapsulatewith

encapsulatewith

accesswith

Page 15: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

BuildingblocksintheModelEntity ValueObject

Haveidentitythatmustbepreserved all alongtheirlife-cycle

Things withinthemodelthatarenotuniquelyidentified

Distinguishedfromothersimilarobjectsbytheiridentityandnotbasedintheirproperties

A pairofvalueobjectsareequalifthevalueoftheirpropertiesmatch

Theirpropertiesaremutable Are immutable,i.e.replaceratherthanupdate

Involvestructureandbehavior(encapsulatedomainlogic)

Involve alsostructureandsomeadditionalvalidationlogic

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 14

Page 16: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Backtoourrunningexample

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 15

Aboutassociations:• Mindtraversaldirections• Eliminatenonessential

associations• Uncovercomposition

relations(stronglifecycledependencies)

ClassifytheclassesinyourdomainmodelasEntitiesorValueobjects

☛ Inthefigure,entities areshowningreyandvalueobjectsinblue

Page 17: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Aggregates• Anaggregateisaclusterofentitiesandvalueobjects,treatedasonesingleunit◦ IthasonerootentitythatisknownastheAggregateRoot

◦ Externalobjectsinteractwiththeaggregateonlyviatheaggregateroot

◦ Asaresultoftheabove◦ Anyrequiredchangeonthe internalobjectsisalwaysmediatedbytheaggregateroot!

◦ Theaggregaterootisresponsibleforensuringaggregateinvariants

• Notethatanyentities/valueobjectwithinanaggregatecanrefertootherexternalentities

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 16

Page 18: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Aggregates inourrunningexample

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 17

reservation1

maintPlan

0..1

0..1

rental

reservation0..1

1 plant

1plant

Page 19: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Moreonaggregates

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 18

Page 20: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Repositories• Arepositoryisanabstractionoverthepersistencesupport◦ Providesbasicoperationsforstoring/retrievingobjectsofanaggregate

◦ Promotesacleanseparationbetweendomainandthetechnicalissuesrelatedtopersistencemanagement

◦ Definesaunitofwork◦ Arepositoryisusuallyassociatedwithonesingledatasource◦ Incaseofmultipledatasources,thetransactionboundaryshouldbetheaggregateitself

• Althoughnotarule,wewillprefertouseasinglerepositoryperaggregate◦ Notalwaysappropriate:Howcanwechecktheavailabilityofplants?

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 19

Page 21: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Examplerepository

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 20

Page 22: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Specificationpattern

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 21

expr

1

components

*

Page 23: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Specificationpattern

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 22

public List<Invoice> selectSatisfying(InvoiceSpecification spec) {List<Invoice> result = new ArrayList();

for (Invoice invoice: invoiceRepo.findAll())if (spec.isSatisfiedBy(invoice)) result.add(invoice);

return result;}

invoices = invoiceRepository.selectSatisfying(new DelinquentInvoice());

Page 24: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

DomainmodelandDataaccess

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 23

Page 25: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

SimpleMapping

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 24

@Entitypublic class Plant {

@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;private String name;@Column(name="DESC")private String description;private Float price;@Lobprivate Image photo;

}

PLANT

ID NAME DESC PRICE PHOTO

Page 26: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Mappingofassociations

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 25

PLANT

ID NAME DESC PRICE

Plant

name: Stringdescription: Stringprice: Float

PurchaseOrderLine

start: Dateend: DatelineTotal: Float

PurchaseOrder

contact: Stringtotal: Float

PURCHASEORDERLINE

ID STARTD ENDD LINETOTAL PLANT_ID

@Entitypublic class PurchaseOrderLine {

@ManyToOneprivate Plant plant;

}

Page 27: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Mappingofassociations

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 26

PURCHASEORDER

ID CONT TOTAL

Plant

name: Stringdescription: Stringprice: Float

PurchaseOrderLine

start: Dateend: DatelineTotal: Float

PurchaseOrder

contact: Stringtotal: Float

PURCHASEORDERLINE

ID START END LINETOTAL PLANT

@Entitypublic class PurchaseOrder {

@OneToMany(cascade = CascadeType.ALL)private Set<PurchaseOrderLine> poLines

= new HashSet<PurchaseOrderLine>();

}

enum CascadeType {ALL, MERGE, PERSIST, REFRESH, REMOVE

}

PO_POL

PO_ID POL_ID

Page 28: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

Queryingdomainobjects

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 27

Page 29: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

BasicqueryingwithSpringDatarepositories

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 28

@Repositorypublic interface PlantRepository extends JpaRepository<Plant, Long> {

List<Plant> findByNameLikeAndPriceBetween(String name, Float low, Float hi);}

@Repositorypublic interface PlantRepository extends JpaRepository<Plant, Long> {

@Query("select p from Plant p " +"where p.name like ?1 and p.price between ?2 and ?3")

List<Plant> finderMethod(String name, Float low, Float hi);}

Textual operators

And Or Between LessThan

GreaterThan After Before IsNull

IsNotNull/NotNull Like NotLike StartingWith

EndingWith Containing OrderBy Not

In NotIn True False

Page 30: MTAT.03.229 Enterprise System Integration...Hexagonal architecture DDD & DATA ACCESS LUCIANO GARCÍA-BAÑUELOS 2 Application Domain model REST adapter SOAP adapter Mem JPA adapter

QueryDSL

DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 29

plantRepo.findAll(nameContains("Mini").and(isAvailableFor(period)))