Queries in Spring Data MongoDB

This commit is contained in:
coach88 2015-08-07 10:46:27 +03:00
parent 00eb2fd02c
commit b0d5516b03
7 changed files with 306 additions and 5 deletions

View File

@ -66,6 +66,12 @@
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-mongodb</artifactId>
<version>${querydsl.version}</version>
</dependency>
</dependencies>
<build>
@ -89,6 +95,7 @@
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version>
<rest-assured.version>2.4.1</rest-assured.version>
<querydsl.version>3.6.6</querydsl.version>
<org.slf4j.version>1.7.12</org.slf4j.version>
<logback.version>1.1.3</logback.version>

View File

@ -0,0 +1,12 @@
package org.baeldung.event;
import org.baeldung.model.User;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
public class BeforeConvertListener extends AbstractMongoEventListener<User> {
@Override
public void onBeforeConvert(User user) {
System.out.println("stop");
}
}

View File

@ -0,0 +1,20 @@
package org.baeldung.model;
import javax.annotation.Generated;
import com.mysema.query.types.path.EntityPathBase;
import com.mysema.query.types.path.StringPath;
@Generated("com.mysema.query.codegen.EntitySerializer")
public class QUser extends EntityPathBase<User> {
private static final long serialVersionUID = 1L;
public static final QUser user = new QUser("user");
public final StringPath name = createString("name");
public QUser(String variable) {
super(User.class, variable);
}
}

View File

@ -1,8 +1,19 @@
package org.baeldung.repository;
import org.baeldung.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface UserRepository extends MongoRepository<User, String> {
//
import org.baeldung.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
public interface UserRepository extends MongoRepository<User, String>, QueryDslPredicateExecutor<User> {
@Query("{ 'name' : ?0 }")
List<User> findUsersByName(String name);
@Query(value = "{'age':?0}", fields = "{ 'name' : 1}")
List<String> findUsersByAgeAndReturnNames(int age);
List<User> findByAgeBetween(int ageGT, int ageLT);
}

View File

@ -9,7 +9,8 @@
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd"
>
<context:annotation-config/>
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost"/>
</bean>
@ -22,5 +23,8 @@
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<mongo:repositories base-package="org.baeldung.repository" mongo-template-ref="mongoTemplate"/>
<bean class="org.baeldung.event.BeforeConvertListener">
</bean>
</beans>

View File

@ -0,0 +1,131 @@
package org.baeldung.mongotemplate;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.baeldung.config.MongoConfig;
import org.baeldung.model.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class MongoTemplateQueryIntegrationTest {
@Autowired
private MongoTemplate mongoTemplate;
@Before
public void testSetup() {
mongoTemplate.createCollection(User.class);
}
@After
public void tearDown() {
mongoTemplate.dropCollection(User.class);
}
@Test
public void givenUsersExist_whenFindingUserWithAgeLessThan50AndGreateThan20_thenUsersAreFound() {
User user = new User();
user.setName("Eric");
user.setAge(45);
mongoTemplate.insert(user);
user = new User();
user.setName("Antony");
user.setAge(55);
mongoTemplate.insert(user);
Query query = new Query();
query.addCriteria(Criteria.where("age").lt(50).gt(20));
List<User> users = mongoTemplate.find(query, User.class);
assertThat(users.size(), is(1));
}
@Test
public void givenUsersExist_whenFindingUserWithNameStartWithA_thenUsersAreFound() {
User user = new User();
user.setName("Eric");
user.setAge(45);
mongoTemplate.insert(user);
user = new User();
user.setName("Antony");
user.setAge(33);
mongoTemplate.insert(user);
user = new User();
user.setName("Alice");
user.setAge(35);
mongoTemplate.insert(user);
Query query = new Query();
query.addCriteria(Criteria.where("name").regex("^A"));
List<User> users = mongoTemplate.find(query, User.class);
assertThat(users.size(), is(2));
}
@Test
public void givenUsersExist_whenFindingByPage_thenUsersAreFoundByPage() {
User user = new User();
user.setName("Eric");
user.setAge(45);
mongoTemplate.insert(user);
user = new User();
user.setName("Antony");
user.setAge(33);
mongoTemplate.insert(user);
user = new User();
user.setName("Alice");
user.setAge(35);
mongoTemplate.insert(user);
final Pageable pageableRequest = new PageRequest(0, 2);
Query query = new Query();
query.with(pageableRequest);
List<User> users = mongoTemplate.find(query, User.class);
assertThat(users.size(), is(2));
}
@Test
public void givenUsersExist_whenFindingUsersAndSortThem_thenUsersAreFoundAndSorted() {
User user = new User();
user.setName("Eric");
user.setAge(45);
mongoTemplate.insert(user);
user = new User();
user.setName("Antony");
user.setAge(33);
mongoTemplate.insert(user);
user = new User();
user.setName("Alice");
user.setAge(35);
mongoTemplate.insert(user);
Query query = new Query();
query.with(new Sort(Sort.Direction.ASC, "age"));
List<User> users = mongoTemplate.find(query, User.class);
assertThat(users.size(), is(3));
}
}

View File

@ -0,0 +1,116 @@
package org.baeldung.repository;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.baeldung.config.MongoConfig;
import org.baeldung.model.QUser;
import org.baeldung.model.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mysema.query.types.Predicate;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class MongoRepositoryQueryIntegrationTest {
@Autowired
private UserRepository userRepository;
@Autowired
private MongoOperations mongoOps;
@Before
public void testSetup() {
mongoOps.createCollection(User.class);
}
@After
public void tearDown() {
mongoOps.dropCollection(User.class);
}
@Test
public void givenUsersExist_whenFindingUsersByName_thenUsersAreFound() {
User user = new User();
user.setName("Jon");
mongoOps.insert(user);
user = new User();
user.setName("Jon");
mongoOps.insert(user);
user = new User();
user.setName("Jim");
mongoOps.insert(user);
List<User> users = userRepository.findUsersByName("Jon");
assertThat(users.size(), is(2));
}
@Test
public void givenUsersExist_whenFindingUsersByAgeAndReturningNames_thenUsersAreFoundAndReturnedNames() {
User user = new User();
user.setName("Jon");
user.setAge(20);
mongoOps.insert(user);
user = new User();
user.setName("Jon");
user.setAge(30);
mongoOps.insert(user);
user = new User();
user.setName("Jim");
user.setAge(40);
mongoOps.insert(user);
List<String> users = userRepository.findUsersByAgeAndReturnNames(30);
assertThat(users.size(), is(1));
}
@Test
public void givenUsersExist_whenFindingUsersWithAgeCreaterThanAndLessThan_thenUsersAreFound() {
User user = new User();
user.setAge(20);
user.setName("Jon");
mongoOps.insert(user);
user = new User();
user.setAge(50);
user.setName("Jon");
mongoOps.insert(user);
user = new User();
user.setAge(33);
user.setName("Jim");
mongoOps.insert(user);
List<User> users = userRepository.findByAgeBetween(26, 40);
assertThat(users.size(), is(1));
}
@Test
public void givenUsersExist_whenFindingUsersAndCount_thenUserAreFound() {
User user = new User();
user.setName("Alexey");
mongoOps.insert(user);
QUser qUser = new QUser("user");
Predicate predicate = qUser.name.eq("Alexey");
List<User> users = (List<User>) userRepository.findAll(predicate);
assertThat(users.size(), is(1));
}
}