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

MongoDB for Java Developers: The Ultimate Sprin...

MongoDB for Java Developers: The Ultimate Spring Data MongoDB Starter Kit

Unleash the combined power of MongoDB and Spring to build your Java applications efficiently. This talk will introduce you to the fundamentals of using Spring Boot, a leading framework in the Java ecosystem, and Spring Data MongoDB to quickly create MongoDB-backed applications and simplify database interactions.

By the end of the presentation, you will have a basic understanding of Spring Data repositories for MongoDB and how the integration works.

Christoph Strobl

October 02, 2024
Tweet

More Decks by Christoph Strobl

Other Decks in Programming

Transcript

  1. MongoDB for Java Developers The Ultimate Spring Data MongoDB Starter

    Kit Christoph Strobl, R&D Engineer, Broadcom Copyright © 2005-2024 Broadcom, Inc. or its affiliates.
  2. Spring Data MongoDB JPA JDBC Neo4j R2DBC ArangoDB Couchbase Cosmos

    DB yugabyteDB Elasticsearch Apache Cassandra ….
  3. Spring Data offers Familiar & Consistent Programming Model That Respects

    Store Specific Traits no silver bullet no magic not one API to rule them all
  4. Entity Manager Template API Mapping Conversion Resource & Transaction
 Management

    native store format <> domain type eg. enum -> string Default Implementation Repository Interface List<Employee> findByFirstName(String name) Repository Anatomy
  5. Entity Manager Template API Mapping Conversion Resource & Transaction
 Management

    native store format <> domain type eg. enum -> string Default Implementation Repository Interface List<Employee> findByFirstName(String name) Repository Anatomy
  6. Entity Manager Database Driver Template API Mapping Conversion Resource &

    Transaction
 Management native store format <> domain type eg. enum -> string Default Implementation Repository Interface List<Employee> findByFirstName(String name) Repository Anatomy
  7. Entity Manager Database Driver Template API Mapping Conversion Resource &

    Transaction
 Management native store format <> domain type eg. enum -> string Default Implementation Repository Interface List<Employee> findByFirstName(String name) MongoClient Repository Anatomy
  8. interface Repo<Employee, String> extends . . . { Repository CrudRepository

    findAll(); findById(...) count(); save(...); delete(...); ... PagingAndSorting Repository findAll(Page); findAll(Sort); Repository Composition
  9. interface Repo<Employee, String> extends . . . { Repository CrudRepository

    findAll(); findById(...) count(); save(...); delete(...); ... PagingAndSorting Repository findAll(Page); findAll(Sort); Proxy Default Implementation Store Specific Repository Composition
  10. interface Repo<Employee, String> extends . . . { Repository CrudRepository

    findAll(); findById(...) count(); save(...); delete(...); ... PagingAndSorting Repository findAll(Page); findAll(Sort); Proxy Default Implementation Store Specific List<Employee> f i ndAll(); long count(); Predefined methods List<Employee> f i ndByFirstName(String name); Derived Finder Method Repository Composition
  11. Break It Down 24 List<Employee> f i ndEmployeeByFirstNameLikeOrderByAgeAsc(String name) Employee

    Page<Employee> Slice<Employee> Stream<Employee> Window<Employee>
  12. Break It Down 25 List<Employee> f i ndEmployeeByFirstNameLikeOrderByAgeAsc(String name) read

    get query search stream Placeholder For Anything You Like Delimiter Employee Page<Employee> Slice<Employee> Stream<Employee> Window<Employee>
  13. Break It Down 26 List<Employee> f i ndEmployeeByFirstNameLikeOrderByAgeAsc(String name) read

    get query search stream Placeholder For Anything You Like matches contains lessThan startsWith greaterThan isEmpty isNull isNotNull before after ... Match Operator Delimiter Employee Page<Employee> Slice<Employee> Stream<Employee> Window<Employee>
  14. Break It Down 27 List<Employee> f i ndEmployeeByFirstNameLikeOrderByAgeAsc(String name) read

    get query search stream Placeholder For Anything You Like matches contains lessThan startsWith greaterThan isEmpty isNull isNotNull before after ... Match Operator Sort Direction Delimiter Employee Page<Employee> Slice<Employee> Stream<Employee> Window<Employee>
  15. Template APIs class MongoTemplate implements MongoOperations { <T> List<T> f

    i nd(Query query, Class<T> entityClass) <T> List<T> f i ndAndRemove(Query query, Class<T> entityClass) <T> T execute(Class<?> entityClass, CollectionCallback<T> callback) query(where(“firstName”).is(...)) template.execute(Employee.class, collection - > { return collection.f i nd(new Document("f i rstname", " .. . ")) .into(new ArrayList()); }); Access to native driver commands MongoDB
  16. class Employee { Long id; String f i rstName; String

    lastName; } class Manager { Long id; String name; List<Employee> employees } { _id : 1000, name : Marvin, employees : [ { id : 1, f i rstName : Ford, lastName : Prefect } , … ] } Basic Mapping MongoDB db.manager
  17. @Document("managers") @Sharded(shardKey = { "country" }) class Manager { @Id

    Long id; String country; @Indexed @Field("full_name") String name; @Version Long version; @CreatedDate Instant created; @EncryptedField(altKeyName="secret",…) String ssn; @DBRef List<Employee> employees; @DocumentReference Supervisor supervisor; { _id : 1000, country : space full_name : Marvin, version: 2, created: 1725879207729, ssn: *****, employees : [ { $ref : employee, $id : … }, … ], supervisor: 42 } db.managers Mapping MongoDB Advanced
  18. Would it save you a lot of time if I

    just gave up and went mad now? Douglas Adams, The Hitchhiker's Guide to the Galaxy
  19. Specific Features MongoDB @Hint("lastname - idx") List<Employee> f i ndByLastname(String

    lastname); @Query(value="{ 'f i rst_name' : ?0 }", f i elds="{ 'f i rst_name' : 1, 'last_name' : 1}") List<Employee> f i ndByFirstname(String f i rstname);
  20. Specific Features MongoDB @Hint("lastname - idx") List<Employee> f i ndByLastname(String

    lastname); @Query(value="{ 'f i rst_name' : ?0 }", f i elds="{ 'f i rst_name' : 1, 'last_name' : 1}") List<Employee> f i ndByFirstname(String f i rstname); @ReadPreference("secondaryPreferred") List<Employee> f i ndByFirstname(String f i rstname);
  21. Specific Features MongoDB @Hint("lastname - idx") List<Employee> f i ndByLastname(String

    lastname); @Query(value="{ 'f i rst_name' : ?0 }", f i elds="{ 'f i rst_name' : 1, 'last_name' : 1}") List<Employee> f i ndByFirstname(String f i rstname); @ReadPreference("secondaryPreferred") List<Employee> f i ndByFirstname(String f i rstname); List<Employee> f i ndByLocationNear(Point location, Distance distance); GeoResults<Employee> f i ndByLocationNear(Point location, Distance distance);
  22. Specific Features MongoDB @Hint("lastname - idx") List<Employee> f i ndByLastname(String

    lastname); @Query(value="{ 'f i rst_name' : ?0 }", f i elds="{ 'f i rst_name' : 1, 'last_name' : 1}") List<Employee> f i ndByFirstname(String f i rstname); @ReadPreference("secondaryPreferred") List<Employee> f i ndByFirstname(String f i rstname); List<Employee> f i ndByLocationNear(Point location, Distance distance); GeoResults<Employee> f i ndByLocationNear(Point location, Distance distance); @Update("{ '$inc' : { 'visits' : 1 } }") long f i ndAndIncrementVisitsByLastname(String lastname);
  23. Specific Features MongoDB @Hint("lastname - idx") List<Employee> f i ndByLastname(String

    lastname); @Query(value="{ 'f i rst_name' : ?0 }", f i elds="{ 'f i rst_name' : 1, 'last_name' : 1}") List<Employee> f i ndByFirstname(String f i rstname); @ReadPreference("secondaryPreferred") List<Employee> f i ndByFirstname(String f i rstname); List<Employee> f i ndByLocationNear(Point location, Distance distance); GeoResults<Employee> f i ndByLocationNear(Point location, Distance distance); @Update("{ '$inc' : { 'visits' : 1 } }") long f i ndAndIncrementVisitsByLastname(String lastname); List<Manager> deleteByLastname(String lastname);
  24. I‘d far rather be happy than right any day. Douglas

    Adams, The Hitchhiker's Guide to the Galaxy
  25. Extension API interface AtlasRepository<T> { List<T> vectorSearch(String index, String path,

    List<Double> vector, Limit limit); } class AtlasRepositoryImpl implements AtlasRepository<T>, RepositoryMetadataAccess { @Autowired MongoOperations mongoOperations; @Override public List<T> vectorSearch(String index, String path, List<Double> vector, Limit limit) { RepositoryMethodContext metadata = RepositoryMethodContext.currentMethod(); Class<?> domainType = metadata.getRepository().getDomainType(); Document $vectorSearch = …; Aggregation aggregation = newAggregation(ctx - > $vectorSearch); return mongoOperations.aggregate(aggregation, domainType).getMappedResults(); } } 1. Define it 2. Implement it
  26. Extension API interface AtlasRepository<T> { List<T> vectorSearch(String index, String path,

    List<Double> vector, Limit limit); } class AtlasRepositoryImpl implements AtlasRepository<T>, RepositoryMetadataAccess { @Autowired MongoOperations mongoOperations; @Override public List<T> vectorSearch(String index, String path, List<Double> vector, Limit limit) { RepositoryMethodContext metadata = RepositoryMethodContext.currentMethod(); Class<?> domainType = metadata.getRepository().getDomainType(); Document $vectorSearch = …; Aggregation aggregation = newAggregation(ctx - > $vectorSearch); return mongoOperations.aggregate(aggregation, domainType).getMappedResults(); } } interface MovieRepository extends CrudRepository<Movie>, AtlasRepository<Movie> { } 1. Define it 2. Implement it 2. Use it