Upgrade to Pro — share decks privately, control downloads, hide ads and more …

MongoNYC 2012: MongoDB for Java Devs with Sprin...

mongodb
May 25, 2012
540

MongoNYC 2012: MongoDB for Java Devs with Spring Data

MongoNYC 2012: MongoDB for Java Devs with Spring Data, Mark Pollack, Vmware. This talk will introduce the Spring Data MongoDB project. Spring Data MongoDB provides a feature rich library for writing MongoDB applications in Java. It builds upon the Spring Framework and as such promotes a POJO programming model with a strong emphasis on productivity. The Spring MongoDB Project provides a rich object mapper, a MongoTemplate helper class to simplify common document access operations using query, criteria, and update DSLs, automatic repository interface implementations, QueryDSL integration, and cross-store persistence.

mongodb

May 25, 2012
Tweet

Transcript

  1. 1 1 © 2010 SpringSource, A division of VMware. All

    rights reserved © 2010 SpringSource, A division of VMware. All rights reserved Spring Data - MongoDB Mark Pollack - VMware
  2. 2 2 About the Speaker § Open Source Development •

    Spring committer since 2003 • Founder of Spring.NET • Lead Spring Data Family of projects § Before… • TIBCO, Reuters, Financial Services Startup • Large scale data collection/analysis in High Energy Physics (~15 yrs ago)
  3. 3 3 Spring Data: Background and Motivation § Data access

    landscape has changed considerably § RDBMS are still important and predominant • but no longer considered a “one size fits all” solution § Spring has always provided excellent data access support • Transaction abstractions, Data access exceptions • JDBC – JdbcTemplate • ORM - Hibernate, JPA support • OXM - Object to XML mapping • Cache support (Spring 3.1) § Spring Data project goal is to “refresh” Spring’s data support
  4. … provide a familiar and consistent Spring based programming model

    while retaining store- specifc features and capabilities
  5. 8 8 Spring Data MongoDB - Feature overview § MongoTemplate

    • Access specific MongoDB operations: geo, map-reduce, upsert • Fluent Query, Criteria, Update APIs • Exception translation to Spring’s DAO exception hierarcy § Object-Document Mapping § Repository support § QueryDSL § Cross-store persistence • Part of object lives in MongoDB, other in RDBMS § JMX § Log4J Logging Adapter § GeoSpatial support § GridFS integration
  6. 9 9 Standard MongoDB API usage pattern § Create and

    store Mongo singleton § Externalize server details § Inserts/Updates • Map application POJO -> DBObject • mongo.getDatabase(…).getCollection(…).save(…) § Queries • Construct query • mongo.getDatabase(…).getCollection(…).find(…) • Iterate through Cursor • Map DBObject -> application POJO(s) § Exception handling  Higher-level than JDBC coding but still repetitive …
  7. 13 13 Other MongoTemplate operations… § findAndModify § findAndRemove §

    findById § findOne § geoNear § group § mapReduce § updateFirst § updateMulti § Upsert § GridFS
  8. Repository Mediates between the domain and data mapping layers using

    a collection-like interface for accessing domain objects. http://martinfowler.com/eaaCatalog/repository.html http://msdn.microsoft.com/en-us/library/ff649690.aspx
  9. Spring Data Repository • Generic repository implementation • CDI integration

    for repositories • Basic CRUD (create, read, update and delete) methods • Generating code for dynamic fnd methods defned in repository interface like fndByName, fndByAgeBetween etc. • Pagination and sorting support • Currently JPA, Mongo and Neo4j implementations
  10. 17 17 Spring Data Repositories public interface CrudRepository<T, ID extends

    Serializable> extends Repository<T, ID> { T save(T entity); Iterable<T> save(Iterable<? extends T> entities); T findOne(ID id); boolean exists(ID id); Iterable<T> findAll(); long count(); void delete(ID id); void delete(T entity); void delete(Iterable<? extends T> entities); void deleteAll(); } public interface Repository<T, ID extends Serializable> { }
  11. 18 18 Spring Data Repositories public interface PagingAndSortingRepository<T, ID extends

    Serializable> extends CrudRepository<T, ID> { Iterable<T> findAll(Sort sort); Page<T> findAll(Pageable pageable); } § Can also avoid use of Spring specific repository interface • Method signatures need to match those in Spring repository interfaces § Query methods use method naming conventions to define query public interface PersonRepository extends CrudRepository<Person,BigInteger> { // Finder for a single entity Person findByEmailAddress(String emailAddress); // Finder for a multiple entities List<Person> findByLastnameLike(String lastName); // Finder with pagination Page<Person> findByFirstnameLike(String firstName, Pageable page); }
  12. 23 23 Spring Data Mongo - Repositories § Based on

    Repository infrastructure in Spring Data Commons • Just define the interface and the namespace configuration
  13. 25 25 QueryDSL § “Querydsl is a framework which enables

    the construction of type- safe SQL-like queries for multiple backends including JPA, JDO, MongoDB, Lucence, SQL and plain collections in Java” • http://www.querydsl.com/ • Open Source, Apache 2.0 § Code completion in IDE § Almost no syntactically invalid queries allowed § Domain types and properties can be references safely (no Strings) § Helper classes generated via Java annotation processor
  14. 31 31 More information § General Spring Data: • http://www.springsource.org/spring-data

    § Spring Data Mongo • Source: https://github.com/SpringSource/spring-data-mongodb • Home Page: http://www.springsource.org/spring-data/mongodb • Forum: http://forum.springsource.org/forumdisplay.php?f=80
  15. 34 34 Spring Data JPA – Entity Mapping § Just

    define the interface: • Spring provides implementation of PersonRepository <jpa:repositories base-package="com.acme.repository" /> @Entity public class Person { @Id @GeneratedValue(strategy=GenerationType.AUTO) private BigInteger id; private String firstname, lastname; @Column(name="email") private String emailAddress; @OneToMany private Set<Person> colleagues; }
  16. 35 35 Spring Data JPA § Wire into your transactional

    service layer as normal @Service public class DefaultUserManagementService implements UserManagementService { public PersonRepository personRepository; public ShiftRepository shiftRepository; @Autowired public DefaultUserManagementService(PersonRepository personRepository, ShiftRepository shiftRepository) { this.personRepository = personRepository; this.shiftRepository = shiftRepository; } @Transactional public void assignToNightShift(String emailAddress) { Person person = personRepository.findByEmailAddress(emailAddress); // continue processing } }
  17. 36 36 Spring Data JPA § Query methods use method

    naming conventions • Can override with Query annotation • Or method name references JPA named query. public interface PersonRepository extends CrudRepository<Person,BigInteger> { // previous methods omitted… @Query("select p from Person p where p.emailAddress = ?1") Person findByEmailAddress(String emailAddress); @Query("select p from Person p where p.firstname = :firstname or p.lastname = :lastname") Person findByLastnameOrFirstname(@Param("lastname") String lastname, @Param("firstname") String firstname); }