SlideShare a Scribd company logo
Apache Cayenne for WO Devs
by Andrus Adamchik, ObjectStyle LLC
• 2001 - inception
• 2002 - first “alpha” release and a large production deployment
• 2006 - Cayenne becomes “Apache Cayenne”
• still active and evolving...
History
• A top-level project at Apache Software Foundation
• 17 committers
• 9 PMC members
• Majority of PMC have WO/EOF background
• ... not all are active ...
Project Structure and
Governance
Releases
• 3.0 - current stable
• 3.1 - Beta, recommended for all users
• 3.2 - in development; used for this presentation
Mapping Structure
Separate DB and Object Layers
DB layer: DbEntities containing DbAttributes and
connected with DbRlationships
• DbEntity - models a table or a view
• DbAttribute - models a column
• DbRelationship - models PK/FK relationship going in one
direction
Object layer: ObjEntities containing ObjAttributes
and connected with ObjRlationships
• ObjEntity - models a persistent Java class
• ObjAttribute - models a “simple” property of a Java class
• ObjRelationship - models a “relationship” property, i.e. a
property of type that is another ObjEntity (can be to-one or to-
many). Going in one direction only.
Connecting Obj to Db Layer
• ObjEntity references a single DbEntity
Connecting Obj to Db Layer
• (simple attribute) ObjAttribute references a DbAttribute
• (flattened attribute) ObjAttribute references a “dbpath” across
one or more DbRelationships ending with an attribute
Connecting Obj to Db Layer
• (simple relationship) ObjRelationship references a
DbRelationship
• (flattened relationship) ObjRelationship references a “dbpath”
across 2 or more DbRelationships
CayenneModeler
Cross-platform natively-packaged tool
to work on Cayenne mapping projects
Tools > Reengineer Database Schema
Tools > Generate Database Schema
Tools > Migrate Schema
Tools > Generate Classes
Tools > Import EOModel
Modeling Workflow
Challenge - keeping these in sync:
Maven and Ant Tools
• cgen - generates classes from the ORM model
• cdbimport - generates model from DB
• cdbgen - generates DB from the model
Modeler Workflow
... on project start:
Modeler Workflow
... on each iteration:
Modeler-Free Workflow
... on project start:
Modeler-Free Workflow
... on each iteration:
Modeler-free Workflow - Maven
<plugin>
	 <groupId>org.apache.cayenne.plugins</groupId>
	 <artifactId>maven-cayenne-plugin</artifactId>
	 <configuration>
	 	 <map>${project.basedir}/src/main/resources/my.map.xml</map>
	 	 <destDir>${project.basedir}/src/main/java</destDir>
	 	 <defaultPackage>com.example.cayenne</defaultPackage>
	 	 <superPkg>com.example.cayenne.auto</superPkg>
	 	 <url>jdbc:mysql://127.0.0.1/mydb</url>
	 	 <username>user</username>
	 	 <password>secret</password>
	 	 <driver>com.mysql.jdbc.Driver</driver>
	 	 <excludeTables>migrations</excludeTables>
	 </configuration>
	 <executions>
	 	 <execution>
	 	 	 <id>default-cli</id>
	 	 	 <goals>
	 	 	 	 <goal>cdbimport</goal>
	 	 	 	 <goal>cgen</goal>
	 	 	 </goals>
	 	 </execution>
	 </executions>
</plugin>
When to use Modeler-free
workflow?
• when DB objects have sane naming
• when DB has FK constraints defined
• when no per-entity model tweaking is needed (optimistic
locking, PK generation, exclusion of attributes, etc.)
Writing Apps with Cayenne
Starting Cayenne
// create reusable ‘runtime’ instance
ServerRuntime runtime = new ServerRuntime("cayenne-myproject.xml");
Stopping Cayenne
runtime.shutdown();
ObjectContext
Obtaining ObjectContext
// regular context
ObjectContext context = runtime.newContext();
// nested context
ObjectContext nestedContext = runtime.newContext(context);
ObjectContext
• An isolated “session” to access Cayenne
• Has its own copy of each object
• Doesn’t require explicit shutdown (can be simply thrown away
when no longer in use)
• Can be serialized
• Can be scoped differently based on app requirements
Under the Hood ServerRuntime
is a DI container
Overriding a DI service to create custom
ObjectContexts
public class MyContextFactory implements ObjectContextFactory {
@Inject
private EventManager eventManager;
	 @Override
	 public ObjectContext createContext() {
	 	 return new MyContext(eventManager);
	 }
	 @Override
	 public ObjectContext createContext(DataChannel parent) {
	 	 return new MyContext(parent, eventManager);
	 }
}
Module myModule = new Module() {
	 @Override
	 public void configure(Binder binder) {
	 	 binder.bind(ObjectContextFactory.class).to(MyContextFactory.class);
	 }
};
// override built-in services via a custom module
ServerRuntime runtime = new ServerRuntime("cayenne-myproject.xml", myModule);
DI Container Highlights
• Very small - 40K
• Intended to make Cayenne runtime modular and customizable
• Does not interfere with or care about application DI
• Can be used outside Cayenne, but this was not the goal
Queries
SelectQuery
• Most commonly used query
• Data rows option
• Fetch offset/limit
• Prefetching (separate strategies)
• Result caching, pagination
• Iterated result
SelectQuery
ObjectContext context = ...
SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class);
List<Artist> allArtists = context.select(query);
SelectQuery with qualifier
ObjectContext context = ...
SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class);
query.andQualifier(Artist.NAME.like("A%"));
query.andQualifier(Artist.DATE_OF_BIRTH.lt(new Date()));
List<Artist> someArtists = context.select(query);
INFO: SELECT t0.NAME, t0.DATE_OF_BIRTH, t0.ID FROM ARTIST t0 WHERE (t0.NAME LIKE ?) AND (t0.DATE_OF_BIRTH < ?)
[bind: 1->NAME:'A%', 2->DATE_OF_BIRTH:'2013-05-09 20:51:12.759']
INFO: === returned 1 row. - took 2 ms.
Other Queries
• EJBQLQuery
• SQLTemplate
• ProcedureQuery
• ObjectIdQuery, RelationshipQuery, QueryChain
• Custom queries...
Caching Query Results
Can be used with any Query and is fairly transparent
SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class);
query.andQualifier(Artist.ARTIST_NAME.like("A%"));
// This is all it takes to cache the result.
// There’s no need to calculate a cache key.
// Cayenne will do that for you
query.useLocalCache();
List<Artist> someArtists = context.select(query);
Lifecycle Events
• PostAdd, PrePersist, PreUpdate, PreRemove, PostPersist,
PostUpdate, PostRemove, PostLoad
• Persistent objects can declare callback methods to be notified
about own events
• Any non-persistent object can be a listener for various entity
events.
Lifecycle Events
• Higher-level “workflows” are implemented by matching entities
with listeners using custom annotations and providing operation
context via DataChannelFilter
Remote Object Persistence
(ROP)
ROP Highlights
• Same as nested ObjectContext, only child context lives in a
remote JVM
• Full ORM API and behavior available on the client:
• Queries, lazy relationships, caching, pagination, etc.
• Client objects based on the same model as server
• Client objects are using a different superclass
Other ORM Choices
• Hibernate
• JPA
Cayenne Difference - Object Design
Others
enhanced/proxied POJO	

ORM Annotations
Cayenne
framework superclass	

annotations used for other things
Advantage
faster startup times
“WYSIWYG” objects
generic persistent objects
less code clutter
Cayenne Difference - Runtime
Others explicit transactions
Cayenne on-demand implicit transactions
Advantage
less code, cleaner code
seamless relationship navigation
EOF Analogies
“All characters and events – even those based on real people
– are entirely fictional.”
Persistent Objects
• EOEnterpriseObject : Persistent, DataObject, CayenneDataObject
• EOGlobalID : ObjectId
• EOGenericRecord : CayenneDataObject
Mapping
• EOModel : DataMap
• EOModelGroup : EntityResolver
• EOEntity: DbEntity / ObjEntity
Query
• EOFetchSpecification : SelectQuery
• EOQualifier : Expression
• EOSortOrdering : Ordering
Runtime
• EOEditingContext : ObjectContext
• EOAdapter : DataNode
• JDBCPlugin : DbAdapter
Cayenne != EOF
WhatYou Might Miss from EOF
• QuirkyVertical Inheritance
• No Horizontal Inheritance
• No prototypes
• No Eclipse plugin
WhatYou Get in Return
• Multithreading
• IDE-independent Modeler
• Internal dependency injection
• Query abstraction beyond
SelectQuery
• EJBQL and aggregated queries
• Iterated query
• Transparent Query result cache
• Transparent Query result pagination
• Auto-increment PK
• Automated DB type detection
• Prefetch strategies
• Lifecycle events
A chance to influence things!
Q&A
Andrus Adamchik
andrus@objectstyle.com
twitter.com/andrus_a
Ad

Recommended

PDF
COScheduler
WO Community
 
PDF
Deployment of WebObjects applications on FreeBSD
WO Community
 
PDF
Practical ERSync
WO Community
 
PDF
D2W Branding Using jQuery ThemeRoller
WO Community
 
PDF
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Thorben Janssen
 
KEY
Using ActiveObjects in Atlassian Plugins
Atlassian
 
PDF
Laravel 8 export data as excel file with example
Katy Slemon
 
PDF
D2W Stateful Controllers
WO Community
 
PPTX
Getting started with ReactJS
Krishna Sunuwar
 
PDF
Staying Sane with Drupal (A Develper's Survival Guide)
Oscar Merida
 
PDF
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
mfrancis
 
PPT
Java EE revisits design patterns
Alex Theedom
 
PDF
Build Amazing Add-ons for Atlassian JIRA and Confluence
K15t
 
PDF
Play framework
Andrew Skiba
 
PDF
Hibernate Presentation
guest11106b
 
PPTX
Real World MVC
James Johnson
 
PDF
20151010 my sq-landjavav2a
Ivan Ma
 
PPT
An introduction to maven gradle and sbt
Fabio Fumarola
 
PDF
SBT Crash Course
Michal Bigos
 
PPTX
Getting started with sbt
ikenna4u
 
PDF
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 
PDF
Connect 2016-Move Your XPages Applications to the Fast Lane
Howard Greenberg
 
PDF
In memory OLAP engine
WO Community
 
PDF
JPA and Hibernate Performance Tips
Vlad Mihalcea
 
KEY
Geotalk presentation
Eric Palakovich Carr
 
PPT
Java build tool_comparison
Manav Prasad
 
PDF
My "Perfect" Toolchain Setup for Grails Projects
GR8Conf
 
PDF
iOS for ERREST
WO Community
 
PDF
Reenabling SOAP using ERJaxWS
WO Community
 

More Related Content

What's hot (20)

PPTX
Getting started with ReactJS
Krishna Sunuwar
 
PDF
Staying Sane with Drupal (A Develper's Survival Guide)
Oscar Merida
 
PDF
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
mfrancis
 
PPT
Java EE revisits design patterns
Alex Theedom
 
PDF
Build Amazing Add-ons for Atlassian JIRA and Confluence
K15t
 
PDF
Play framework
Andrew Skiba
 
PDF
Hibernate Presentation
guest11106b
 
PPTX
Real World MVC
James Johnson
 
PDF
20151010 my sq-landjavav2a
Ivan Ma
 
PPT
An introduction to maven gradle and sbt
Fabio Fumarola
 
PDF
SBT Crash Course
Michal Bigos
 
PPTX
Getting started with sbt
ikenna4u
 
PDF
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 
PDF
Connect 2016-Move Your XPages Applications to the Fast Lane
Howard Greenberg
 
PDF
In memory OLAP engine
WO Community
 
PDF
JPA and Hibernate Performance Tips
Vlad Mihalcea
 
KEY
Geotalk presentation
Eric Palakovich Carr
 
PPT
Java build tool_comparison
Manav Prasad
 
PDF
My "Perfect" Toolchain Setup for Grails Projects
GR8Conf
 
Getting started with ReactJS
Krishna Sunuwar
 
Staying Sane with Drupal (A Develper's Survival Guide)
Oscar Merida
 
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
mfrancis
 
Java EE revisits design patterns
Alex Theedom
 
Build Amazing Add-ons for Atlassian JIRA and Confluence
K15t
 
Play framework
Andrew Skiba
 
Hibernate Presentation
guest11106b
 
Real World MVC
James Johnson
 
20151010 my sq-landjavav2a
Ivan Ma
 
An introduction to maven gradle and sbt
Fabio Fumarola
 
SBT Crash Course
Michal Bigos
 
Getting started with sbt
ikenna4u
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 
Connect 2016-Move Your XPages Applications to the Fast Lane
Howard Greenberg
 
In memory OLAP engine
WO Community
 
JPA and Hibernate Performance Tips
Vlad Mihalcea
 
Geotalk presentation
Eric Palakovich Carr
 
Java build tool_comparison
Manav Prasad
 
My "Perfect" Toolchain Setup for Grails Projects
GR8Conf
 

Viewers also liked (16)

PDF
iOS for ERREST
WO Community
 
PDF
Reenabling SOAP using ERJaxWS
WO Community
 
PDF
Using Nagios to monitor your WO systems
WO Community
 
PDF
Build and deployment
WO Community
 
PDF
Migrating existing Projects to Wonder
WO Community
 
PDF
Filtering data with D2W
WO Community
 
PDF
WOver
WO Community
 
PDF
Advanced Apache Cayenne
WO Community
 
PDF
Chaining the Beast - Testing Wonder Applications in the Real World
WO Community
 
PDF
Life outside WO
WO Community
 
PDF
Unit Testing with WOUnit
WO Community
 
PDF
iOS for ERREST - alternative version
WO Community
 
PDF
KAAccessControl
WO Community
 
PDF
Deploying WO on Windows
WO Community
 
PDF
High availability
WO Community
 
PDF
"Framework Principal" pattern
WO Community
 
iOS for ERREST
WO Community
 
Reenabling SOAP using ERJaxWS
WO Community
 
Using Nagios to monitor your WO systems
WO Community
 
Build and deployment
WO Community
 
Migrating existing Projects to Wonder
WO Community
 
Filtering data with D2W
WO Community
 
Advanced Apache Cayenne
WO Community
 
Chaining the Beast - Testing Wonder Applications in the Real World
WO Community
 
Life outside WO
WO Community
 
Unit Testing with WOUnit
WO Community
 
iOS for ERREST - alternative version
WO Community
 
KAAccessControl
WO Community
 
Deploying WO on Windows
WO Community
 
High availability
WO Community
 
"Framework Principal" pattern
WO Community
 
Ad

Similar to Apache Cayenne for WO Devs (20)

PPT
Apache Persistence Layers
Henning Schmiedehausen
 
PPTX
Apache Cayenne: a Java ORM Alternative
Andrus Adamchik
 
PDF
ITB2017 - Slaying the ORM dragons with cborm
Ortus Solutions, Corp
 
PDF
Илья Драбеня - Apache Cayenne Intro
Minsk Linux User Group
 
PDF
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
Ortus Solutions, Corp
 
PDF
Killing Shark-Riding Dinosaurs with ORM
Ortus Solutions, Corp
 
PDF
ORM Pink Unicorns
Ortus Solutions, Corp
 
PDF
Easy ORM-ness with Objectify-Appengine - Indicthreads cloud computing confere...
IndicThreads
 
PDF
Using Document Databases with TYPO3 Flow
Karsten Dambekalns
 
KEY
Object Relational Mapping in PHP
Rob Knight
 
PDF
Luis Majano The Battlefield ORM
Ortus Solutions, Corp
 
PDF
OrientDB the database for the web 1.1
Luca Garulli
 
PPTX
Hibernate tutorial
Mumbai Academisc
 
PPTX
ColdFusion ORM - Part II
Rupesh Kumar
 
PPTX
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
PPT
Hibernate basics
AathikaJava
 
PPT
Java Hibernate Basics
DeeptiJava
 
PDF
Cassandra: An Alien Technology That's not so Alien
Brian Hess
 
PPTX
Hibernate in XPages
Toby Samples
 
PDF
Building Asynchronous Applications
Johan Edstrom
 
Apache Persistence Layers
Henning Schmiedehausen
 
Apache Cayenne: a Java ORM Alternative
Andrus Adamchik
 
ITB2017 - Slaying the ORM dragons with cborm
Ortus Solutions, Corp
 
Илья Драбеня - Apache Cayenne Intro
Minsk Linux User Group
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
Ortus Solutions, Corp
 
Killing Shark-Riding Dinosaurs with ORM
Ortus Solutions, Corp
 
ORM Pink Unicorns
Ortus Solutions, Corp
 
Easy ORM-ness with Objectify-Appengine - Indicthreads cloud computing confere...
IndicThreads
 
Using Document Databases with TYPO3 Flow
Karsten Dambekalns
 
Object Relational Mapping in PHP
Rob Knight
 
Luis Majano The Battlefield ORM
Ortus Solutions, Corp
 
OrientDB the database for the web 1.1
Luca Garulli
 
Hibernate tutorial
Mumbai Academisc
 
ColdFusion ORM - Part II
Rupesh Kumar
 
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
Hibernate basics
AathikaJava
 
Java Hibernate Basics
DeeptiJava
 
Cassandra: An Alien Technology That's not so Alien
Brian Hess
 
Hibernate in XPages
Toby Samples
 
Building Asynchronous Applications
Johan Edstrom
 
Ad

More from WO Community (10)

PDF
Localizing your apps for multibyte languages
WO Community
 
PDF
WOdka
WO Community
 
PDF
ERGroupware
WO Community
 
PDF
CMS / BLOG and SnoWOman
WO Community
 
PDF
Using GIT
WO Community
 
PDF
Persistent Session Storage
WO Community
 
PDF
Back2 future
WO Community
 
PDF
WebObjects Optimization
WO Community
 
PDF
Dynamic Elements
WO Community
 
PDF
ERRest: the Basics
WO Community
 
Localizing your apps for multibyte languages
WO Community
 
ERGroupware
WO Community
 
CMS / BLOG and SnoWOman
WO Community
 
Using GIT
WO Community
 
Persistent Session Storage
WO Community
 
Back2 future
WO Community
 
WebObjects Optimization
WO Community
 
Dynamic Elements
WO Community
 
ERRest: the Basics
WO Community
 

Recently uploaded (20)

PDF
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
PDF
The Growing Value and Application of FME & GenAI
Safe Software
 
PPTX
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
PDF
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
PDF
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
PDF
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
PDF
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
PDF
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
PDF
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
PPTX
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
PPTX
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
PDF
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
PDF
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
PDF
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
PDF
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
PPTX
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
PDF
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
PDF
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
The Growing Value and Application of FME & GenAI
Safe Software
 
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Python Conference Singapore - 19 Jun 2025
ninefyi
 

Apache Cayenne for WO Devs

  • 1. Apache Cayenne for WO Devs by Andrus Adamchik, ObjectStyle LLC
  • 2. • 2001 - inception • 2002 - first “alpha” release and a large production deployment • 2006 - Cayenne becomes “Apache Cayenne” • still active and evolving... History
  • 3. • A top-level project at Apache Software Foundation • 17 committers • 9 PMC members • Majority of PMC have WO/EOF background • ... not all are active ... Project Structure and Governance
  • 4. Releases • 3.0 - current stable • 3.1 - Beta, recommended for all users • 3.2 - in development; used for this presentation
  • 6. Separate DB and Object Layers
  • 7. DB layer: DbEntities containing DbAttributes and connected with DbRlationships • DbEntity - models a table or a view • DbAttribute - models a column • DbRelationship - models PK/FK relationship going in one direction
  • 8. Object layer: ObjEntities containing ObjAttributes and connected with ObjRlationships • ObjEntity - models a persistent Java class • ObjAttribute - models a “simple” property of a Java class • ObjRelationship - models a “relationship” property, i.e. a property of type that is another ObjEntity (can be to-one or to- many). Going in one direction only.
  • 9. Connecting Obj to Db Layer • ObjEntity references a single DbEntity
  • 10. Connecting Obj to Db Layer • (simple attribute) ObjAttribute references a DbAttribute • (flattened attribute) ObjAttribute references a “dbpath” across one or more DbRelationships ending with an attribute
  • 11. Connecting Obj to Db Layer • (simple relationship) ObjRelationship references a DbRelationship • (flattened relationship) ObjRelationship references a “dbpath” across 2 or more DbRelationships
  • 13. Cross-platform natively-packaged tool to work on Cayenne mapping projects
  • 14. Tools > Reengineer Database Schema
  • 15. Tools > Generate Database Schema
  • 16. Tools > Migrate Schema
  • 17. Tools > Generate Classes
  • 18. Tools > Import EOModel
  • 20. Challenge - keeping these in sync:
  • 21. Maven and Ant Tools • cgen - generates classes from the ORM model • cdbimport - generates model from DB • cdbgen - generates DB from the model
  • 22. Modeler Workflow ... on project start:
  • 23. Modeler Workflow ... on each iteration:
  • 25. Modeler-Free Workflow ... on each iteration:
  • 26. Modeler-free Workflow - Maven <plugin> <groupId>org.apache.cayenne.plugins</groupId> <artifactId>maven-cayenne-plugin</artifactId> <configuration> <map>${project.basedir}/src/main/resources/my.map.xml</map> <destDir>${project.basedir}/src/main/java</destDir> <defaultPackage>com.example.cayenne</defaultPackage> <superPkg>com.example.cayenne.auto</superPkg> <url>jdbc:mysql://127.0.0.1/mydb</url> <username>user</username> <password>secret</password> <driver>com.mysql.jdbc.Driver</driver> <excludeTables>migrations</excludeTables> </configuration> <executions> <execution> <id>default-cli</id> <goals> <goal>cdbimport</goal> <goal>cgen</goal> </goals> </execution> </executions> </plugin>
  • 27. When to use Modeler-free workflow? • when DB objects have sane naming • when DB has FK constraints defined • when no per-entity model tweaking is needed (optimistic locking, PK generation, exclusion of attributes, etc.)
  • 28. Writing Apps with Cayenne
  • 29. Starting Cayenne // create reusable ‘runtime’ instance ServerRuntime runtime = new ServerRuntime("cayenne-myproject.xml");
  • 32. Obtaining ObjectContext // regular context ObjectContext context = runtime.newContext(); // nested context ObjectContext nestedContext = runtime.newContext(context);
  • 33. ObjectContext • An isolated “session” to access Cayenne • Has its own copy of each object • Doesn’t require explicit shutdown (can be simply thrown away when no longer in use) • Can be serialized • Can be scoped differently based on app requirements
  • 34. Under the Hood ServerRuntime is a DI container
  • 35. Overriding a DI service to create custom ObjectContexts public class MyContextFactory implements ObjectContextFactory { @Inject private EventManager eventManager; @Override public ObjectContext createContext() { return new MyContext(eventManager); } @Override public ObjectContext createContext(DataChannel parent) { return new MyContext(parent, eventManager); } } Module myModule = new Module() { @Override public void configure(Binder binder) { binder.bind(ObjectContextFactory.class).to(MyContextFactory.class); } }; // override built-in services via a custom module ServerRuntime runtime = new ServerRuntime("cayenne-myproject.xml", myModule);
  • 36. DI Container Highlights • Very small - 40K • Intended to make Cayenne runtime modular and customizable • Does not interfere with or care about application DI • Can be used outside Cayenne, but this was not the goal
  • 38. SelectQuery • Most commonly used query • Data rows option • Fetch offset/limit • Prefetching (separate strategies) • Result caching, pagination • Iterated result
  • 39. SelectQuery ObjectContext context = ... SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class); List<Artist> allArtists = context.select(query);
  • 40. SelectQuery with qualifier ObjectContext context = ... SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class); query.andQualifier(Artist.NAME.like("A%")); query.andQualifier(Artist.DATE_OF_BIRTH.lt(new Date())); List<Artist> someArtists = context.select(query); INFO: SELECT t0.NAME, t0.DATE_OF_BIRTH, t0.ID FROM ARTIST t0 WHERE (t0.NAME LIKE ?) AND (t0.DATE_OF_BIRTH < ?) [bind: 1->NAME:'A%', 2->DATE_OF_BIRTH:'2013-05-09 20:51:12.759'] INFO: === returned 1 row. - took 2 ms.
  • 41. Other Queries • EJBQLQuery • SQLTemplate • ProcedureQuery • ObjectIdQuery, RelationshipQuery, QueryChain • Custom queries...
  • 43. Can be used with any Query and is fairly transparent SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class); query.andQualifier(Artist.ARTIST_NAME.like("A%")); // This is all it takes to cache the result. // There’s no need to calculate a cache key. // Cayenne will do that for you query.useLocalCache(); List<Artist> someArtists = context.select(query);
  • 44. Lifecycle Events • PostAdd, PrePersist, PreUpdate, PreRemove, PostPersist, PostUpdate, PostRemove, PostLoad • Persistent objects can declare callback methods to be notified about own events • Any non-persistent object can be a listener for various entity events.
  • 45. Lifecycle Events • Higher-level “workflows” are implemented by matching entities with listeners using custom annotations and providing operation context via DataChannelFilter
  • 47. ROP Highlights • Same as nested ObjectContext, only child context lives in a remote JVM • Full ORM API and behavior available on the client: • Queries, lazy relationships, caching, pagination, etc. • Client objects based on the same model as server • Client objects are using a different superclass
  • 48. Other ORM Choices • Hibernate • JPA
  • 49. Cayenne Difference - Object Design Others enhanced/proxied POJO ORM Annotations Cayenne framework superclass annotations used for other things Advantage faster startup times “WYSIWYG” objects generic persistent objects less code clutter
  • 50. Cayenne Difference - Runtime Others explicit transactions Cayenne on-demand implicit transactions Advantage less code, cleaner code seamless relationship navigation
  • 51. EOF Analogies “All characters and events – even those based on real people – are entirely fictional.”
  • 52. Persistent Objects • EOEnterpriseObject : Persistent, DataObject, CayenneDataObject • EOGlobalID : ObjectId • EOGenericRecord : CayenneDataObject
  • 53. Mapping • EOModel : DataMap • EOModelGroup : EntityResolver • EOEntity: DbEntity / ObjEntity
  • 54. Query • EOFetchSpecification : SelectQuery • EOQualifier : Expression • EOSortOrdering : Ordering
  • 55. Runtime • EOEditingContext : ObjectContext • EOAdapter : DataNode • JDBCPlugin : DbAdapter
  • 57. WhatYou Might Miss from EOF • QuirkyVertical Inheritance • No Horizontal Inheritance • No prototypes • No Eclipse plugin
  • 58. WhatYou Get in Return • Multithreading • IDE-independent Modeler • Internal dependency injection • Query abstraction beyond SelectQuery • EJBQL and aggregated queries • Iterated query • Transparent Query result cache • Transparent Query result pagination • Auto-increment PK • Automated DB type detection • Prefetch strategies • Lifecycle events
  • 59. A chance to influence things!