Spring Data MongoDB Cheatsheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Sold to

Spring Data MongoDB CheatSheet


[email protected]

Using Spring Boot

Dependency Configure Database Configuration

<dependency> Configure DB in application properties (


. or yaml) By default, all @Document andRepository are scanned, starting at the

<groupId>org.springframework.boot</groupId> location your main @Configuration


<artifactId>spring-boot-starter-data-mongodb</artifactId> spring.data.mongodb.uri=mongodb://localhost:27017/tutorial
</dependency> spring.data.mongodb.username=user @EnableMongoRepositories : Scans and sets up Repositories

spring.data.mongodb.password=myfancypassword
Example:

@EnableMongoRepositories("de.codeboje.example.repos")

Domain Model Repository

Create an interface and extend from Repository


@Document : defines a model @Document
@Id : primary key public class User { Example:

@Field : additional field config

@DBRef : reference model in another @Id public interface UserRepository extends PagingAndSortingRepository<User, Long>{
collection private Long id; }

private String username; Special Repositories

}
CrudRepository : adds basic CRUD methods

PagingAndSortingRepository : adds paging and sorting methods

Query

Defined on Repository methods

By Method Naming Using @Query Annotation Paging

findBy, findAllBy, followed by fieldnames joined MongoDB JSON query is passed in the parameter Pass a parameter of type Pageable and return Page
using AND, OR, etc

@Query("{ 'firstname' : ?0 }") Page<User> findAllByLastname(String lastname, Pageable page);


findAllByLastname(String lastname); List<User> findAllByLastname(String lastname);

findFirstByCreationDate Sorting

findAllByCityOrderByZipCode Pass a parameter of type Sort

List<User> findAllByLastname(String lastname, Sort sort);

codeboje.de

You might also like