Your SlideShare is downloading. ×
Mongo sf   easy java persistence
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Mongo sf easy java persistence

1,047
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,047
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
8
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. Morphia: Easy Java Persistence
    Scott Hernandez @ 10gen
  • 2. Library Choices
    Raw MongoDB Driver
    Map<String, Object> view of objects
    Rough but dynamic
    Morphia (type-safe mapper)
    POJOs
    Annotation based (similar to JPA)
    Syntactic sugar and helpers
    Others
    Code generators, other jvm languages
  • 3. MongoDB Java Driver
    BSON Package
    Types
    Encode/Decode
    DBObject (Map<String, Object>)
    Nested Maps
    Directly encoded to binary format (BSON)
    MongoDB Package
    Mongo
    DBObject (BasicDBObject/Builder)
    DB/DBColletion
    DBQuery/DBCursor
  • 4. BSON Package
    Types
    int and long
    Array/ArrayList
    String
    byte[] – binData
    Double (IEEE 754 FP)
    Date (secs since epoch)
    Null
    Boolean
    JavaScript String
    Regex
  • 5. MongoDB Package
    Mongo
    Connection, ThreadSafe
    WriteConcern*
    DB
    Auth, Collections
    getLastError()
    Command(), eval()
    RequestStart/Done
    DBCollection
    Insert/Save/Find/Remove/Update/FindAndModify
    ensureIndex
  • 6. Simple Example
    DBCollectioncoll = new Mongo().getDB(“test”);
    coll.save(
    new BasicDBObjectBuilder(“name”, “scott”).
    append(“sex”, “male”).
    append(“height”, 178)).get());
  • 7. Simple Example, Again
    DBCollectioncoll = new Mongo().getDB(“test”).getCollection(“people”);
    Map<String, Object> fields = new …
    fields.add(“name”, “scott”);
    fields.add(“sex”, “male”);
    fields.add(“height”, 178);
    coll.insert(new BasicDBObject(fields));
  • 8. DBObject <-> (B/J)SON
    {name:”scott”, sex:“male”, height: 178 }
    new BasicDBObjectBuilder()
    .append(“name”, “scott”)
    .append(“sex”, “male”)
    .append(“height”, 178) .get();
    String name = (String)dbObj.get(“name”);
  • 9. Lists
    DBObjectdbObj = JSON.parse(“
    {‘name’:’scott’,height: 178, sex:’male’}
    ”);
    List<String> activities = new …
    activities.add(“mongodb”);
    activities.add(“java”);
    dbObj.put(“activities”, activities);
    {…, activities: [‘mongodb’, ‘java’]}
  • 10. Maps of Maps
    Can represent object graph/tree
    Always keyed off String (field)
  • 11. Morphia: MongoDB Mapper
    Maps POJO (through fields)
    Type-safe/preserving
    Access Patterns: DAO/Datastore/+more
    Data Types
    Performs well
    JPA like
    Many concepts came from Objectify (GAE)
  • 12. Annotations
    @Entity(“collectionName”)
    @Id
    @Reference
    [@Embedded]
    • @Serialized
    @Transient – not java transient
    @Property(“fieldAlias”)
  • 13. Annotations -- continued
    @Indexes(@Index(…), @Index(…))
    @Indexed(…)
    @AlsoLoad([aliases])
    @NotSaved()
    @ConstructorAgs([field-names])
  • 14. Basic POJO
    @Entity
    class Person {
    @Id
    String name;
    SexEnum sex;
    @Indexed
    Integer height;
    }
  • 15. Lifecycle Events
    @PrePersist
    @PreSave
    @PostPersist
    @PreLoad
    @PostLoad
    @EntityListeners
    EntityInterceptor (global)
  • 16. Lifecycle Methods
    @Entity
    class Person {
    @Id String name;

    Date updated;
    @PrePersist
    void prePersist() {
    updated = new Date();
    }
    }
  • 17. Datastore Basics
    get(class, id) – single Entity by id
    find(class, […]) – multiple Entities (by query)
    save(entity, […])
    delete(query)
    getCount(query) – also find(…).count()
    update/First(query, ops)
    findAndModify/Delete(query, ops)
    merge(doc)
    mapReduce(type, query, map, reduce, …)
    EnsureIndexes()/EnsureCaps()
  • 18. Save whole object graphs (get/save)
    Update parts (embedded objects)
    Un/set fields
    Push/pop arrays (lists)
    Increment numeric fields
    Any combination of the above
    Merge
    Get/Save or Update
  • 19. Add, Get, Delete
    Person me = new Person(“scott”, Sex.Male, 179)
    Datastoreds = new Morphia().createDatastore(“bar”)
    ds.save(me);
    Person meAgain = ds.get(Person.class, “scott”)
    ds.delete(me);
  • 20. Queries
    Based on Entity (Class)
    Validated (default)
    Fluent
    Or and Geo Support
    Type Converted Params
    Reusable
    Returned as
    Keys (or @Id only instances)
    List
    Iterable
  • 21. Simple Query
    Datastoreds = …
    Query q = ds.createQuery(Person.class);
    q.field(“height”).greaterThan(155).limit(5);
    for(Person p : q.fetch())
    print(p);
    Person me = q.field(“name”).startsWith(“sc”).get();
  • 22. Update
    Datastoreds = …
    Query q = ds.find(Person.class, “name”, “scott”);
    UpdateOperationuo = ds.createUpdateOperations(cls)
    uo.set(“city”, “seattle”).set(“lastUpdated”, new Date());
    UpdateResults res = ds.update(q, uo);
    if(res.getUpdatedCount() > 0)
    //do something?
  • 23. Update Operations
    set(field, val)
    unset(field)
    inc(field, [val])
    dec(field)
    add(field, val)
    addAll(field, vals)
    removeFirst/Last(field)
    removeAll(field, vals)
  • 24. Relationships
    [@Embedded]
    Loaded/Saved with Entity
    Update
    @Reference
    Stored as DBRef(s)
    Loaded with Entity
    Not automatically saved
    Lazy (w/proxy)
    Key<T>
    Stored as DBRef(s)
    Just a link, but resolvable by Datastore/Query
  • 25. Questions?
    Checkout Morphia:
    http://code.google.com/p/morphia
    ScottHernandez@gmail.com

×