Apache Cayenne for WO Devs
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
2,739
On Slideshare
2,739
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
13
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Apache Cayenne for WO Devsby 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 andGovernance
  • 4. Releases• 3.0 - current stable• 3.1 - Beta, recommended for all users• 3.2 - in development; used for this presentation
  • 5. Mapping Structure
  • 6. Separate DB and Object Layers
  • 7. DB layer: DbEntities containing DbAttributes andconnected with DbRlationships• DbEntity - models a table or a view• DbAttribute - models a column• DbRelationship - models PK/FK relationship going in onedirection
  • 8. Object layer: ObjEntities containing ObjAttributesand 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. aproperty 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” acrossone or more DbRelationships ending with an attribute
  • 11. Connecting Obj to Db Layer• (simple relationship) ObjRelationship references aDbRelationship• (flattened relationship) ObjRelationship references a “dbpath”across 2 or more DbRelationships
  • 12. CayenneModeler
  • 13. Cross-platform natively-packaged toolto 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
  • 19. Modeling Workflow
  • 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:
  • 24. Modeler-Free Workflow... on project start:
  • 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-freeworkflow?• when DB objects have sane naming• when DB has FK constraints defined• when no per-entity model tweaking is needed (optimisticlocking, PK generation, exclusion of attributes, etc.)
  • 28. Writing Apps with Cayenne
  • 29. Starting Cayenne// create reusable ‘runtime’ instanceServerRuntime runtime = new ServerRuntime("cayenne-myproject.xml");
  • 30. Stopping Cayenneruntime.shutdown();
  • 31. ObjectContext
  • 32. Obtaining ObjectContext// regular contextObjectContext context = runtime.newContext();// nested contextObjectContext 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 awaywhen no longer in use)• Can be serialized• Can be scoped differently based on app requirements
  • 34. Under the Hood ServerRuntimeis a DI container
  • 35. Overriding a DI service to create customObjectContextspublic class MyContextFactory implements ObjectContextFactory {@Injectprivate 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 moduleServerRuntime 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
  • 37. Queries
  • 38. SelectQuery• Most commonly used query• Data rows option• Fetch offset/limit• Prefetching (separate strategies)• Result caching, pagination• Iterated result
  • 39. SelectQueryObjectContext context = ...SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class);List<Artist> allArtists = context.select(query);
  • 40. SelectQuery with qualifierObjectContext 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...
  • 42. Caching Query Results
  • 43. Can be used with any Query and is fairly transparentSelectQuery<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 youquery.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 notifiedabout own events• Any non-persistent object can be a listener for various entityevents.
  • 45. Lifecycle Events• Higher-level “workflows” are implemented by matching entitieswith listeners using custom annotations and providing operationcontext via DataChannelFilter
  • 46. Remote Object Persistence(ROP)
  • 47. ROP Highlights• Same as nested ObjectContext, only child context lives in aremote 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 DesignOthersenhanced/proxied POJO ORM AnnotationsCayenneframework superclass annotations used for other thingsAdvantagefaster startup times“WYSIWYG” objectsgeneric persistent objectsless code clutter
  • 50. Cayenne Difference - RuntimeOthers explicit transactionsCayenne on-demand implicit transactionsAdvantageless code, cleaner codeseamless 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
  • 56. Cayenne != EOF
  • 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 beyondSelectQuery• 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!
  • 60. Q&AAndrus Adamchikandrus@objectstyle.comtwitter.com/andrus_a