Mongo sf easy java persistence

1,323 views
1,239 views

Published on

Published in: Technology, News & Politics
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,323
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Mongo sf easy java persistence

  1. 1. Morphia: Easy Java Persistence<br />Scott Hernandez @ 10gen<br />
  2. 2. Library Choices<br />Raw MongoDB Driver<br />Map<String, Object> view of objects<br />Rough but dynamic<br />Morphia (type-safe mapper)<br />POJOs<br />Annotation based (similar to JPA)<br />Syntactic sugar and helpers<br />Others<br />Code generators, other jvm languages<br />
  3. 3. MongoDB Java Driver<br />BSON Package<br />Types<br />Encode/Decode<br />DBObject (Map<String, Object>)<br />Nested Maps<br />Directly encoded to binary format (BSON)<br />MongoDB Package<br />Mongo<br />DBObject (BasicDBObject/Builder)<br />DB/DBColletion<br />DBQuery/DBCursor<br />
  4. 4. BSON Package<br />Types<br />int and long<br />Array/ArrayList<br />String<br />byte[] – binData<br />Double (IEEE 754 FP)<br />Date (secs since epoch)<br />Null<br />Boolean<br />JavaScript String<br />Regex<br />
  5. 5. MongoDB Package<br />Mongo<br />Connection, ThreadSafe<br />WriteConcern*<br />DB<br />Auth, Collections <br />getLastError()<br />Command(), eval()<br />RequestStart/Done<br />DBCollection<br />Insert/Save/Find/Remove/Update/FindAndModify<br />ensureIndex<br />
  6. 6. Simple Example<br />DBCollectioncoll = new Mongo().getDB(“test”);<br />coll.save(<br /> new BasicDBObjectBuilder(“name”, “scott”).<br /> append(“sex”, “male”).<br /> append(“height”, 178)).get());<br />
  7. 7. Simple Example, Again<br />DBCollectioncoll = new Mongo().getDB(“test”).getCollection(“people”);<br />Map<String, Object> fields = new …<br />fields.add(“name”, “scott”); <br />fields.add(“sex”, “male”);<br />fields.add(“height”, 178);<br />coll.insert(new BasicDBObject(fields));<br />
  8. 8. DBObject <-> (B/J)SON<br />{name:”scott”, sex:“male”, height: 178 }<br />new BasicDBObjectBuilder()<br />.append(“name”, “scott”) <br />.append(“sex”, “male”) <br />.append(“height”, 178) .get();<br />String name = (String)dbObj.get(“name”); <br />
  9. 9. Lists<br />DBObjectdbObj = JSON.parse(“<br /> {‘name’:’scott’,height: 178, sex:’male’}<br />”);<br />List<String> activities = new …<br />activities.add(“mongodb”);<br />activities.add(“java”);<br />dbObj.put(“activities”, activities);<br />{…, activities: [‘mongodb’, ‘java’]}<br />
  10. 10. Maps of Maps<br />Can represent object graph/tree<br />Always keyed off String (field)<br />
  11. 11. Morphia: MongoDB Mapper<br />Maps POJO (through fields)<br />Type-safe/preserving<br />Access Patterns: DAO/Datastore/+more<br />Data Types<br />Performs well<br />JPA like<br />Many concepts came from Objectify (GAE)<br />
  12. 12. Annotations<br />@Entity(“collectionName”)<br />@Id<br />@Reference<br />[@Embedded]<br /><ul><li>@Serialized</li></ul>@Transient – not java transient<br />@Property(“fieldAlias”)<br />
  13. 13. Annotations -- continued<br />@Indexes(@Index(…), @Index(…))<br />@Indexed(…)<br />@AlsoLoad([aliases])<br />@NotSaved()<br />@ConstructorAgs([field-names])<br />
  14. 14. Basic POJO<br />@Entity<br />class Person {<br />@Id<br /> String name;<br />SexEnum sex;<br />@Indexed<br /> Integer height;<br />} <br />
  15. 15. Lifecycle Events<br />@PrePersist<br />@PreSave<br />@PostPersist<br />@PreLoad<br />@PostLoad<br />@EntityListeners<br />EntityInterceptor (global)<br />
  16. 16. Lifecycle Methods<br />@Entity<br />class Person {<br />@Id String name;<br /> …<br /> Date updated;<br /> @PrePersist<br /> void prePersist() {<br /> updated = new Date();<br /> }<br />} <br />
  17. 17. Datastore Basics<br />get(class, id) – single Entity by id<br />find(class, […]) – multiple Entities (by query)<br />save(entity, […])<br />delete(query) <br />getCount(query) – also find(…).count()<br />update/First(query, ops)<br />findAndModify/Delete(query, ops)<br />merge(doc)<br />mapReduce(type, query, map, reduce, …)<br />EnsureIndexes()/EnsureCaps()<br />
  18. 18. Save whole object graphs (get/save)<br />Update parts (embedded objects)<br />Un/set fields<br />Push/pop arrays (lists)<br />Increment numeric fields<br />Any combination of the above<br />Merge<br />Get/Save or Update<br />
  19. 19. Add, Get, Delete<br />Person me = new Person(“scott”, Sex.Male, 179)<br />Datastoreds = new Morphia().createDatastore(“bar”)<br />ds.save(me);<br />Person meAgain = ds.get(Person.class, “scott”)<br />ds.delete(me);<br />
  20. 20. Queries<br />Based on Entity (Class)<br />Validated (default)<br />Fluent<br />Or and Geo Support<br />Type Converted Params<br />Reusable<br />Returned as <br />Keys (or @Id only instances)<br />List<br />Iterable<br />
  21. 21. Simple Query<br />Datastoreds = …<br />Query q = ds.createQuery(Person.class);<br />q.field(“height”).greaterThan(155).limit(5);<br />for(Person p : q.fetch())<br /> print(p);<br />Person me = q.field(“name”).startsWith(“sc”).get();<br />
  22. 22. Update<br />Datastoreds = …<br />Query q = ds.find(Person.class, “name”, “scott”);<br />UpdateOperationuo = ds.createUpdateOperations(cls)<br />uo.set(“city”, “seattle”).set(“lastUpdated”, new Date());<br />UpdateResults res = ds.update(q, uo);<br />if(res.getUpdatedCount() > 0)<br /> //do something?<br />
  23. 23. Update Operations<br />set(field, val)<br />unset(field)<br />inc(field, [val])<br />dec(field)<br />add(field, val)<br />addAll(field, vals)<br />removeFirst/Last(field)<br />removeAll(field, vals)<br />
  24. 24. Relationships<br />[@Embedded]<br />Loaded/Saved with Entity<br />Update<br />@Reference<br />Stored as DBRef(s)<br />Loaded with Entity<br />Not automatically saved<br />Lazy (w/proxy)<br />Key<T><br />Stored as DBRef(s)<br />Just a link, but resolvable by Datastore/Query<br />
  25. 25. Questions?<br />Checkout Morphia:<br />http://code.google.com/p/morphia<br />ScottHernandez@gmail.com<br />

×