2018-06-02 23:14:27 +03:00
|
|
|
package com.baeldung.mongotemplate;
|
2017-01-28 00:54:49 +05:30
|
|
|
|
2018-06-02 23:14:27 +03:00
|
|
|
import com.baeldung.config.SimpleMongoConfig;
|
|
|
|
|
import com.baeldung.model.User;
|
2017-01-28 00:54:49 +05:30
|
|
|
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.MongoTemplate;
|
|
|
|
|
import org.springframework.data.mongodb.core.query.Query;
|
|
|
|
|
import org.springframework.test.context.ContextConfiguration;
|
|
|
|
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
|
|
|
|
|
2017-07-09 06:27:31 +02:00
|
|
|
import static org.junit.Assert.assertNotNull;
|
|
|
|
|
import static org.junit.Assert.assertNull;
|
|
|
|
|
import static org.junit.Assert.assertTrue;
|
|
|
|
|
|
2017-01-28 00:54:49 +05:30
|
|
|
@RunWith(SpringJUnit4ClassRunner.class)
|
2017-02-09 01:34:42 +02:00
|
|
|
@ContextConfiguration(classes = SimpleMongoConfig.class)
|
2017-01-28 00:54:49 +05:30
|
|
|
public class MongoTemplateProjectionLiveTest {
|
|
|
|
|
|
|
|
|
|
@Autowired
|
|
|
|
|
private MongoTemplate mongoTemplate;
|
|
|
|
|
|
|
|
|
|
@Before
|
|
|
|
|
public void testSetup() {
|
|
|
|
|
if (!mongoTemplate.collectionExists(User.class)) {
|
|
|
|
|
mongoTemplate.createCollection(User.class);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@After
|
|
|
|
|
public void tearDown() {
|
|
|
|
|
mongoTemplate.dropCollection(User.class);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Test
|
|
|
|
|
public void givenUserExists_whenAgeZero_thenSuccess() {
|
|
|
|
|
mongoTemplate.insert(new User("John", 30));
|
|
|
|
|
mongoTemplate.insert(new User("Ringo", 35));
|
|
|
|
|
|
2017-02-09 01:34:42 +02:00
|
|
|
final Query query = new Query();
|
2017-01-28 00:54:49 +05:30
|
|
|
query.fields()
|
2017-07-09 06:27:31 +02:00
|
|
|
.include("name");
|
2017-01-28 00:54:49 +05:30
|
|
|
|
|
|
|
|
mongoTemplate.find(query, User.class)
|
2017-07-09 06:27:31 +02:00
|
|
|
.forEach(user -> {
|
|
|
|
|
assertNotNull(user.getName());
|
|
|
|
|
assertTrue(user.getAge()
|
|
|
|
|
.equals(0));
|
|
|
|
|
});
|
2017-01-28 00:54:49 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Test
|
|
|
|
|
public void givenUserExists_whenIdNull_thenSuccess() {
|
|
|
|
|
mongoTemplate.insert(new User("John", 30));
|
|
|
|
|
mongoTemplate.insert(new User("Ringo", 35));
|
|
|
|
|
|
2017-02-09 01:34:42 +02:00
|
|
|
final Query query = new Query();
|
2017-01-28 00:54:49 +05:30
|
|
|
query.fields()
|
2017-07-09 06:27:31 +02:00
|
|
|
.exclude("_id");
|
2017-01-28 00:54:49 +05:30
|
|
|
|
|
|
|
|
mongoTemplate.find(query, User.class)
|
2017-07-09 06:27:31 +02:00
|
|
|
.forEach(user -> {
|
|
|
|
|
assertNull(user.getId());
|
|
|
|
|
assertNotNull(user.getAge());
|
|
|
|
|
});
|
2017-02-09 01:34:42 +02:00
|
|
|
|
2017-01-28 00:54:49 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|