MTAT.03.229Enterprise System IntegrationLecture 2: Domain model and data access layerLucianoGarcía-BañuelosUnivers i tyof Tartu
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
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
Domain-drivendesign(DDD)• Domain-drivendesign(DDD)isanapproachtodevelopingsoftwarefor complexneeds bydeeplyconnectingtheimplementationtoanevolvingmodelofthecorebusinessconcepts.
• Itspremisesare:◦ A developmentprojectmustprimarilyfocusinthecoredomainanddomainlogic
◦ Themodeliscentraltoanycomplexdesign◦ Thedevelopmentreliesoncreativecollaborationbetween technicalanddomainexperts toiterativelycuteverclosertotheconceptualheartoftheproblem
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 3
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
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
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
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
Exercise:Rentit• Sales◦ Queryingtheplantcatalog◦ Creatingapurchaseorder◦ Processingofapurchaseorder◦ Planttransportation◦ Invoicing
• Maintenance◦ Creationofyearlymaintenanceplan◦ Schedulingofmaintenancetasks
• Reservations◦ Howtocoordinaterentalandmaintenance(implicit)
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 8
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
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
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
Theoverallpicture
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 12
0..1
maintPlan
reservation1
0..1
rental
reservation0..1
1 plantreservation
1
1plant
TacticDesign
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 13
Modeldrivendesign
ServicesEntities
Valueobjects
Modules
Repositories
Aggregates
Factories
accesswithmaintain
integritywithactasrootofencapsulate
withencapsulate
with
encapsulatewith
encapsulatewith
accesswith
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
Backtoourrunningexample
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 15
Aboutassociations:• Mindtraversaldirections• Eliminatenonessential
associations• Uncovercomposition
relations(stronglifecycledependencies)
ClassifytheclassesinyourdomainmodelasEntitiesorValueobjects
☛ Inthefigure,entities areshowningreyandvalueobjectsinblue
Aggregates• Anaggregateisaclusterofentitiesandvalueobjects,treatedasonesingleunit◦ IthasonerootentitythatisknownastheAggregateRoot
◦ Externalobjectsinteractwiththeaggregateonlyviatheaggregateroot
◦ Asaresultoftheabove◦ Anyrequiredchangeonthe internalobjectsisalwaysmediatedbytheaggregateroot!
◦ Theaggregaterootisresponsibleforensuringaggregateinvariants
• Notethatanyentities/valueobjectwithinanaggregatecanrefertootherexternalentities
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 16
Aggregates inourrunningexample
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 17
reservation1
maintPlan
0..1
0..1
rental
reservation0..1
1 plant
1plant
Moreonaggregates
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 18
Repositories• Arepositoryisanabstractionoverthepersistencesupport◦ Providesbasicoperationsforstoring/retrievingobjectsofanaggregate
◦ Promotesacleanseparationbetweendomainandthetechnicalissuesrelatedtopersistencemanagement
◦ Definesaunitofwork◦ Arepositoryisusuallyassociatedwithonesingledatasource◦ Incaseofmultipledatasources,thetransactionboundaryshouldbetheaggregateitself
• Althoughnotarule,wewillprefertouseasinglerepositoryperaggregate◦ Notalwaysappropriate:Howcanwechecktheavailabilityofplants?
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 19
Examplerepository
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 20
Specificationpattern
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 21
expr
1
components
*
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());
DomainmodelandDataaccess
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 23
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
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;
}
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
Queryingdomainobjects
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 27
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
QueryDSL
DDD&DATAACCESSLUCIANOGARCÍA-BAÑUELOS 29
plantRepo.findAll(nameContains("Mini").and(isAvailableFor(period)))