SlideShare uma empresa Scribd logo
1 de 19
copyright 2013 Trainologic LTD
Spring Data and
MongoDB
copyright 2013 Trainologic LTD
Spring Data
• Spring Data provides a set of utilities for working with
NoSQL databases.
• It also provides support for relational databases and
REST interfaces.
• We are going to focus over MongoDB support.
• But first, some basics…
Spring Data
copyright 2013 Trainologic LTD
Spring Data
• Spring Data Commons provides a common API for the
different Spring Data subprojects.
• The main interface in Spring Data is the Repository
interface.
• This is a marker interface that is mainly used for
discovering extending classes.
Data Commons
copyright 2013 Trainologic LTD
Spring Data
• The main interface that extends from Repository is the
CrudRepository one.
• It provides methods for saving, deleting, counting and
retrieving of your domain class.
• Usually a specific storage technology class will be
available that extends this one (e.g., MongoRepository).
• The PagingAndSortingRepository interface provides
paging and sorting capabilities.
CrudRepository
copyright 2013 Trainologic LTD
Spring Data
• If you don’t feel like exposing the entire CrudRepository
interface, you can annotate your class with the
@RepositoryDefinition annotation.
• Then, you can selectively provides the required
methods.
Custom Repositories
copyright 2013 Trainologic LTD
Spring Data
• Spring Data provides a mechanism for generating
custom queries for your storage technology.
• A four steps recipe:
1. Define an interface that extends from the
appropriate repository interface.
2. Add your query signatures.
3. Instruct Spring to create proxy for your repository.
4. Inject the generated bean and use it.
Custom Queries
copyright 2013 Trainologic LTD
Spring Data
Example
public interface MyCompanyRepository extends MongoRepository<Company,
String>{
List<Company> findByCompanyName(String name);
}
copyright 2013 Trainologic LTD
Spring Data
• Spring Data can construct the actual query according to
the method name or by additional declaration.
• If selecting the method name way then:
• The ‘By’ acts as a separator.
• Inherent support for And and Or.
• Support for Between, LessThan, GreaterThan and
Like.
• Support IgnoreCase.
• And OrderBy with additional Asc or Desc.
Query Syntax
copyright 2013 Trainologic LTD
Spring Data
• Query methods can also accept additional special
parameters of the following types:
• Sort – allows to configure a sort operation.
• Pageable – allows to configure paging.
Query Syntax
copyright 2013 Trainologic LTD
Spring Data
• In order to connect your Spring project to
MongoDB, you need to create a connection.
• Can be done with either annotations or XML namespace
(as usual in Spring).
• XML Schema example:
Connecting to MongoDB
<mongo:mongo replica-set="127.0.0.1:27017,localhost:27018">
<mongo:options connections-per-host="8"
threads-allowed-to-block-for-connection-multiplier="4"
connect-timeout="1000“
auto-connect-retry="true
slave-ok="true
write-fsync="true"/>
</mongo:mongo/>
copyright 2013 Trainologic LTD
Spring Data
• MongoDB is a very popular NoSQL Database.
• Spring Data provides many features for easing (the
already easy) programming to MongoDB.
• Two main features:
• MongoTemplate.
• Mongo Repositories.
Spring Data for MongoDB
copyright 2013 Trainologic LTD
Spring Data
• As usual in Spring, template objects are both thread-
safe and stateless. 
• MongoTemplate provides API resembles as possible the
native MongoDB driver for Java.
• The main difference is that the MongoTemplate can
receive your model objects directly and not only
DBObject.
• Your objects are mapped/converted to MongoDB
objects.
MongoTemplate
copyright 2013 Trainologic LTD
Spring Data
• You can configure your MongoTemplate with a
WriteConcernResolver which will allow you to specify a
write-concern on a per operation basis.
MongoTemplate
copyright 2013 Trainologic LTD
Spring Data
• Id mapping is handled as follows:
• Usage of the @Id annotation (not the JPA one).
• A property/field named ‘id’.
• If you don’t define one, the framework will generate an
id for you.
Id
copyright 2013 Trainologic LTD
Spring Data
• The following annotations are provided for mapping:
• @Document, @DBRef, @Indexed, @CompoundIndex,
@GeoSpatialIndexed, @Transient, @PersistenceCons
tructor, @Value, @Field
Supported Domain Mapping
copyright 2013 Trainologic LTD
Spring Data
findAndModify as an Example
• findAndModify receives a query object and an Update
object and allows you to perform the famous
search&update in MongoDB.
copyright 2013 Trainologic LTD
Spring Data
Querying
• You can construct a query object using the following
ways:
• Use Criteria statements.
• Use the BasicQuery object to provide plain ole’ JSON.
copyright 2013 Trainologic LTD
Spring Data
Querying
• If you want to customize the query in a JSON way, you
can use the @Query annotation.
• E.g.:
@Query(value="{ ‘lastName' : ?0 }", fields="{ 'firstName' : 1, 'lastName' : 1}")
List<Student> findStudentsByLastName(String lastName);
copyright 2013 Trainologic LTD
Spring Data
Typesafe Queries
• You can also perform typesafe queries with the Query
DSL.
• However, in order to use it, you should generate DSL
code using APT (resembles typed criteria model from
JPA 2.0).

Mais conteúdo relacionado

Mais procurados

Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)
Kai Zhao
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
chriskite
 

Mais procurados (20)

MongoDB and Hadoop: Driving Business Insights
MongoDB and Hadoop: Driving Business InsightsMongoDB and Hadoop: Driving Business Insights
MongoDB and Hadoop: Driving Business Insights
 
Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
 
Mongodb - NoSql Database
Mongodb - NoSql DatabaseMongodb - NoSql Database
Mongodb - NoSql Database
 
Back to Basics Webinar 1: Introduction to NoSQL
Back to Basics Webinar 1: Introduction to NoSQLBack to Basics Webinar 1: Introduction to NoSQL
Back to Basics Webinar 1: Introduction to NoSQL
 
MongoDB and Spark
MongoDB and SparkMongoDB and Spark
MongoDB and Spark
 
Mongo DB
Mongo DB Mongo DB
Mongo DB
 
Mongo db operations_v2
Mongo db operations_v2Mongo db operations_v2
Mongo db operations_v2
 
CouchDB : More Couch
CouchDB : More CouchCouchDB : More Couch
CouchDB : More Couch
 
Optimize drupal using mongo db
Optimize drupal using mongo dbOptimize drupal using mongo db
Optimize drupal using mongo db
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
An Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDBAn Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB 101
MongoDB 101MongoDB 101
MongoDB 101
 
Mongo-Drupal
Mongo-DrupalMongo-Drupal
Mongo-Drupal
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
 
Get expertise with mongo db
Get expertise with mongo dbGet expertise with mongo db
Get expertise with mongo db
 

Semelhante a Building Spring Data with MongoDB

Semelhante a Building Spring Data with MongoDB (20)

Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Mongodb
MongodbMongodb
Mongodb
 
Mongo db
Mongo dbMongo db
Mongo db
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
 
MongoDB DOC v1.5
MongoDB DOC v1.5MongoDB DOC v1.5
MongoDB DOC v1.5
 
黑豹 ch4 ddd pattern practice (2)
黑豹 ch4 ddd pattern practice (2)黑豹 ch4 ddd pattern practice (2)
黑豹 ch4 ddd pattern practice (2)
 
Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
 
how_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptxhow_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptx
 
SQL vs MongoDB
SQL vs MongoDBSQL vs MongoDB
SQL vs MongoDB
 
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDBMongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB World 2019: Fast Machine Learning Development with MongoDB
 
SQL vs NoSQL, an experiment with MongoDB
SQL vs NoSQL, an experiment with MongoDBSQL vs NoSQL, an experiment with MongoDB
SQL vs NoSQL, an experiment with MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
Extend db
Extend dbExtend db
Extend db
 
how_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdfhow_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdf
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
UNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptxUNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptx
 
Top MongoDB interview Questions and Answers
Top MongoDB interview Questions and AnswersTop MongoDB interview Questions and Answers
Top MongoDB interview Questions and Answers
 
What is the significance of MongoDB and what are its usages.docx
What is the significance of MongoDB and what are its usages.docxWhat is the significance of MongoDB and what are its usages.docx
What is the significance of MongoDB and what are its usages.docx
 
What are the major components of MongoDB and the major tools used in it.docx
What are the major components of MongoDB and the major tools used in it.docxWhat are the major components of MongoDB and the major tools used in it.docx
What are the major components of MongoDB and the major tools used in it.docx
 

Mais de MongoDB

Mais de MongoDB (20)

MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 MongoDB SoCal 2020: MongoDB Atlas Jump Start MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Building Spring Data with MongoDB

  • 1. copyright 2013 Trainologic LTD Spring Data and MongoDB
  • 2. copyright 2013 Trainologic LTD Spring Data • Spring Data provides a set of utilities for working with NoSQL databases. • It also provides support for relational databases and REST interfaces. • We are going to focus over MongoDB support. • But first, some basics… Spring Data
  • 3. copyright 2013 Trainologic LTD Spring Data • Spring Data Commons provides a common API for the different Spring Data subprojects. • The main interface in Spring Data is the Repository interface. • This is a marker interface that is mainly used for discovering extending classes. Data Commons
  • 4. copyright 2013 Trainologic LTD Spring Data • The main interface that extends from Repository is the CrudRepository one. • It provides methods for saving, deleting, counting and retrieving of your domain class. • Usually a specific storage technology class will be available that extends this one (e.g., MongoRepository). • The PagingAndSortingRepository interface provides paging and sorting capabilities. CrudRepository
  • 5. copyright 2013 Trainologic LTD Spring Data • If you don’t feel like exposing the entire CrudRepository interface, you can annotate your class with the @RepositoryDefinition annotation. • Then, you can selectively provides the required methods. Custom Repositories
  • 6. copyright 2013 Trainologic LTD Spring Data • Spring Data provides a mechanism for generating custom queries for your storage technology. • A four steps recipe: 1. Define an interface that extends from the appropriate repository interface. 2. Add your query signatures. 3. Instruct Spring to create proxy for your repository. 4. Inject the generated bean and use it. Custom Queries
  • 7. copyright 2013 Trainologic LTD Spring Data Example public interface MyCompanyRepository extends MongoRepository<Company, String>{ List<Company> findByCompanyName(String name); }
  • 8. copyright 2013 Trainologic LTD Spring Data • Spring Data can construct the actual query according to the method name or by additional declaration. • If selecting the method name way then: • The ‘By’ acts as a separator. • Inherent support for And and Or. • Support for Between, LessThan, GreaterThan and Like. • Support IgnoreCase. • And OrderBy with additional Asc or Desc. Query Syntax
  • 9. copyright 2013 Trainologic LTD Spring Data • Query methods can also accept additional special parameters of the following types: • Sort – allows to configure a sort operation. • Pageable – allows to configure paging. Query Syntax
  • 10. copyright 2013 Trainologic LTD Spring Data • In order to connect your Spring project to MongoDB, you need to create a connection. • Can be done with either annotations or XML namespace (as usual in Spring). • XML Schema example: Connecting to MongoDB <mongo:mongo replica-set="127.0.0.1:27017,localhost:27018"> <mongo:options connections-per-host="8" threads-allowed-to-block-for-connection-multiplier="4" connect-timeout="1000“ auto-connect-retry="true slave-ok="true write-fsync="true"/> </mongo:mongo/>
  • 11. copyright 2013 Trainologic LTD Spring Data • MongoDB is a very popular NoSQL Database. • Spring Data provides many features for easing (the already easy) programming to MongoDB. • Two main features: • MongoTemplate. • Mongo Repositories. Spring Data for MongoDB
  • 12. copyright 2013 Trainologic LTD Spring Data • As usual in Spring, template objects are both thread- safe and stateless.  • MongoTemplate provides API resembles as possible the native MongoDB driver for Java. • The main difference is that the MongoTemplate can receive your model objects directly and not only DBObject. • Your objects are mapped/converted to MongoDB objects. MongoTemplate
  • 13. copyright 2013 Trainologic LTD Spring Data • You can configure your MongoTemplate with a WriteConcernResolver which will allow you to specify a write-concern on a per operation basis. MongoTemplate
  • 14. copyright 2013 Trainologic LTD Spring Data • Id mapping is handled as follows: • Usage of the @Id annotation (not the JPA one). • A property/field named ‘id’. • If you don’t define one, the framework will generate an id for you. Id
  • 15. copyright 2013 Trainologic LTD Spring Data • The following annotations are provided for mapping: • @Document, @DBRef, @Indexed, @CompoundIndex, @GeoSpatialIndexed, @Transient, @PersistenceCons tructor, @Value, @Field Supported Domain Mapping
  • 16. copyright 2013 Trainologic LTD Spring Data findAndModify as an Example • findAndModify receives a query object and an Update object and allows you to perform the famous search&update in MongoDB.
  • 17. copyright 2013 Trainologic LTD Spring Data Querying • You can construct a query object using the following ways: • Use Criteria statements. • Use the BasicQuery object to provide plain ole’ JSON.
  • 18. copyright 2013 Trainologic LTD Spring Data Querying • If you want to customize the query in a JSON way, you can use the @Query annotation. • E.g.: @Query(value="{ ‘lastName' : ?0 }", fields="{ 'firstName' : 1, 'lastName' : 1}") List<Student> findStudentsByLastName(String lastName);
  • 19. copyright 2013 Trainologic LTD Spring Data Typesafe Queries • You can also perform typesafe queries with the Query DSL. • However, in order to use it, you should generate DSL code using APT (resembles typed criteria model from JPA 2.0).