upgrade spring-data-mongodb

This commit is contained in:
DOHA 2018-10-04 22:18:12 +03:00
parent faae433c40
commit e65d77a47a
8 changed files with 158 additions and 108 deletions

View File

@ -8,9 +8,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId> <artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-4</relativePath> <relativePath>../parent-spring-5</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -19,6 +19,28 @@
<artifactId>spring-data-mongodb</artifactId> <artifactId>spring-data-mongodb</artifactId>
<version>${org.springframework.data.version}</version> <version>${org.springframework.data.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Lovelace-M3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-reactivestreams</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.2.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
@ -48,6 +70,17 @@
</dependency> </dependency>
</dependencies> </dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -70,10 +103,11 @@
</build> </build>
<properties> <properties>
<org.springframework.data.version>1.10.4.RELEASE</org.springframework.data.version> <org.springframework.data.version>2.1.0.RELEASE</org.springframework.data.version>
<rest-assured.version>2.9.0</rest-assured.version>
<querydsl.version>4.1.4</querydsl.version> <querydsl.version>4.1.4</querydsl.version>
<mysema.maven.version>1.1.3</mysema.maven.version> <mysema.maven.version>1.1.3</mysema.maven.version>
<spring.version>5.1.0.RELEASE</spring.version>
</properties> </properties>
</project> </project>

View File

@ -1,20 +1,22 @@
package com.baeldung.config; package com.baeldung.config;
import com.mongodb.Mongo; import java.util.ArrayList;
import com.mongodb.MongoClient; import java.util.List;
import com.baeldung.converter.UserWriterConverter;
import com.baeldung.event.CascadeSaveMongoEventListener;
import com.baeldung.event.UserCascadeSaveMongoEventListener;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.convert.CustomConversions; import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.ArrayList; import com.baeldung.converter.UserWriterConverter;
import java.util.List; import com.baeldung.event.CascadeSaveMongoEventListener;
import com.baeldung.event.UserCascadeSaveMongoEventListener;
import com.mongodb.MongoClient;
@Configuration @Configuration
@EnableMongoRepositories(basePackages = "com.baeldung.repository") @EnableMongoRepositories(basePackages = "com.baeldung.repository")
@ -28,7 +30,7 @@ public class MongoConfig extends AbstractMongoConfiguration {
} }
@Override @Override
public Mongo mongo() throws Exception { public MongoClient mongoClient() {
return new MongoClient("127.0.0.1", 27017); return new MongoClient("127.0.0.1", 27017);
} }
@ -57,4 +59,10 @@ public class MongoConfig extends AbstractMongoConfiguration {
public GridFsTemplate gridFsTemplate() throws Exception { public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter()); return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
} }
@Bean
MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
} }

View File

@ -1,18 +1,18 @@
package com.baeldung.config; package com.baeldung.config;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.MongoClient;
@Configuration @Configuration
@EnableMongoRepositories(basePackages = "com.baeldung.repository") @EnableMongoRepositories(basePackages = "com.baeldung.repository")
public class SimpleMongoConfig { public class SimpleMongoConfig {
@Bean @Bean
public Mongo mongo() throws Exception { public MongoClient mongo() throws Exception {
return new MongoClient("localhost"); return new MongoClient("localhost");
} }

View File

@ -1,13 +1,14 @@
package com.baeldung.repository; package com.baeldung.repository;
import com.baeldung.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import java.util.List; import java.util.List;
public interface UserRepository extends MongoRepository<User, String>, QueryDslPredicateExecutor<User> { import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import com.baeldung.model.User;
public interface UserRepository extends MongoRepository<User, String>, QuerydslPredicateExecutor<User> {
@Query("{ 'name' : ?0 }") @Query("{ 'name' : ?0 }")
List<User> findUsersByName(String name); List<User> findUsersByName(String name);

View File

@ -3,17 +3,17 @@
xmlns:p="http://www.springframework.org/schema/p" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd" http://www.springframework.org/schema/context/spring-context.xsd"
> >
<context:annotation-config/> <context:annotation-config/>
<mongo:mongo id="mongo" host="localhost" /> <mongo:mongo-client id="mongoClient" host="localhost" />
<mongo:db-factory id="mongoDbFactory" dbname="test" mongo-ref="mongo" /> <mongo:db-factory id="mongoDbFactory" dbname="test" mongo-ref="mongoClient" />
<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate"> <bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<constructor-arg ref="mongoDbFactory" /> <constructor-arg ref="mongoDbFactory" />
@ -27,12 +27,12 @@
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<mongo:repositories base-package="org.baeldung.repository" mongo-template-ref="mongoTemplate"/> <mongo:repositories base-package="com.baeldung.repository" mongo-template-ref="mongoTemplate"/>
<bean class="org.baeldung.event.CascadeSaveMongoEventListener"> <bean class="com.baeldung.event.CascadeSaveMongoEventListener">
</bean> </bean>
<mongo:mapping-converter id="mongoConverter" base-package="org.baeldung.converter"> <mongo:mapping-converter id="mongoConverter" base-package="com.baeldung.converter">
<mongo:custom-converters base-package="org.baeldung.converter"/> <mongo:custom-converters base-package="org.baeldung.converter"/>
</mongo:mapping-converter> </mongo:mapping-converter>

View File

@ -1,12 +1,24 @@
package com.baeldung.aggregation; package com.baeldung.aggregation;
import com.mongodb.DB; import static org.junit.Assert.assertEquals;
import com.mongodb.DBCollection; import static org.junit.Assert.assertTrue;
import com.mongodb.DBObject; import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import com.mongodb.MongoClient; import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit;
import com.mongodb.util.JSON; import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import com.baeldung.aggregation.model.StatePopulation; import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import com.baeldung.config.MongoConfig; import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.bson.Document;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
@ -26,23 +38,13 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.BufferedReader; import com.baeldung.aggregation.model.StatePopulation;
import java.io.InputStream; import com.baeldung.config.MongoConfig;
import java.io.InputStreamReader; import com.mongodb.DB;
import java.util.ArrayList; import com.mongodb.DBCollection;
import java.util.Collections; import com.mongodb.DBObject;
import java.util.List; import com.mongodb.MongoClient;
import java.util.stream.Collectors; import com.mongodb.util.JSON;
import java.util.stream.StreamSupport;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class) @ContextConfiguration(classes = MongoConfig.class)
@ -140,13 +142,13 @@ public class ZipsAggregationLiveTest {
Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast); Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast);
AggregationResults<DBObject> result = mongoTemplate.aggregate(aggregation, "zips", DBObject.class); AggregationResults<Document> result = mongoTemplate.aggregate(aggregation, "zips", Document.class);
DBObject dbObject = result.getUniqueMappedResult(); Document document = result.getUniqueMappedResult();
assertEquals("DC", dbObject.get("minZipState")); assertEquals("DC", document.get("minZipState"));
assertEquals(24, dbObject.get("minZipCount")); assertEquals(24, document.get("minZipCount"));
assertEquals("TX", dbObject.get("maxZipState")); assertEquals("TX", document.get("maxZipState"));
assertEquals(1671, dbObject.get("maxZipCount")); assertEquals(1671, document.get("maxZipCount"));
} }
} }

View File

@ -1,8 +1,19 @@
package com.baeldung.gridfs; package com.baeldung.gridfs;
import com.mongodb.BasicDBObject; import static org.hamcrest.CoreMatchers.is;
import com.mongodb.DBObject; import static org.hamcrest.Matchers.nullValue;
import com.mongodb.gridfs.GridFSDBFile; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.bson.types.ObjectId;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -16,18 +27,9 @@ import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.FileInputStream; import com.mongodb.BasicDBObject;
import java.io.FileNotFoundException; import com.mongodb.DBObject;
import java.io.IOException; import com.mongodb.client.gridfs.model.GridFSFile;
import java.io.InputStream;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
@ContextConfiguration("file:src/main/resources/mongoConfig.xml") @ContextConfiguration("file:src/main/resources/mongoConfig.xml")
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ -40,8 +42,9 @@ public class GridFSLiveTest {
@After @After
public void tearDown() { public void tearDown() {
List<GridFSDBFile> fileList = gridFsTemplate.find(null); List<GridFSFile> fileList = new ArrayList<GridFSFile>();
for (GridFSDBFile file : fileList) { gridFsTemplate.find(new Query()).into(fileList);
for (GridFSFile file : fileList) {
gridFsTemplate.delete(new Query(Criteria.where("filename").is(file.getFilename()))); gridFsTemplate.delete(new Query(Criteria.where("filename").is(file.getFilename())));
} }
} }
@ -54,7 +57,7 @@ public class GridFSLiveTest {
String id = ""; String id = "";
try { try {
inputStream = new FileInputStream("src/main/resources/test.png"); inputStream = new FileInputStream("src/main/resources/test.png");
id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).toString();
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
logger.error("File not found", ex); logger.error("File not found", ex);
} finally { } finally {
@ -75,10 +78,10 @@ public class GridFSLiveTest {
DBObject metaData = new BasicDBObject(); DBObject metaData = new BasicDBObject();
metaData.put("user", "alex"); metaData.put("user", "alex");
InputStream inputStream = null; InputStream inputStream = null;
String id = ""; ObjectId id = null;
try { try {
inputStream = new FileInputStream("src/main/resources/test.png"); inputStream = new FileInputStream("src/main/resources/test.png");
id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
logger.error("File not found", ex); logger.error("File not found", ex);
} finally { } finally {
@ -91,22 +94,22 @@ public class GridFSLiveTest {
} }
} }
GridFSDBFile gridFSDBFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
assertNotNull(gridFSDBFile); assertNotNull(gridFSFile);
assertNotNull(gridFSDBFile.getInputStream()); // assertNotNull(gridFSFile.getInputStream());
assertThat(gridFSDBFile.numChunks(), is(1)); // assertThat(gridFSFile.numChunks(), is(1));
assertThat(gridFSDBFile.containsField("filename"), is(true)); // assertThat(gridFSFile.containsField("filename"), is(true));
assertThat(gridFSDBFile.get("filename"), is("test.png")); assertThat(gridFSFile.getFilename(), is("test.png"));
assertThat(gridFSDBFile.getId(), is(id)); assertThat(gridFSFile.getObjectId(), is(id));
assertThat(gridFSDBFile.keySet().size(), is(9)); // assertThat(gridFSFile.keySet().size(), is(9));
assertNotNull(gridFSDBFile.getMD5()); // assertNotNull(gridFSFile.getMD5());
assertNotNull(gridFSDBFile.getUploadDate()); assertNotNull(gridFSFile.getUploadDate());
assertNull(gridFSDBFile.getAliases()); // assertNull(gridFSFile.getAliases());
assertNotNull(gridFSDBFile.getChunkSize()); assertNotNull(gridFSFile.getChunkSize());
assertThat(gridFSDBFile.getContentType(), is("image/png")); assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png"));
assertThat(gridFSDBFile.getFilename(), is("test.png")); assertThat(gridFSFile.getFilename(), is("test.png"));
assertThat(gridFSDBFile.getMetaData().get("user"), is("alex")); assertThat(gridFSFile.getMetadata().get("user"), is("alex"));
} }
@Test @Test
@ -133,10 +136,11 @@ public class GridFSLiveTest {
} }
} }
List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(null); List<GridFSFile> gridFSFiles = new ArrayList<GridFSFile>();
gridFsTemplate.find(new Query()).into(gridFSFiles);
assertNotNull(gridFSDBFiles); assertNotNull(gridFSFiles);
assertThat(gridFSDBFiles.size(), is(2)); assertThat(gridFSFiles.size(), is(2));
} }
@Test @Test
@ -163,10 +167,11 @@ public class GridFSLiveTest {
} }
} }
List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(new Query(Criteria.where("metadata.user").is("alex"))); List<GridFSFile> gridFSFiles = new ArrayList<GridFSFile>();
gridFsTemplate.find(new Query(Criteria.where("metadata.user").is("alex"))).into(gridFSFiles);
assertNotNull(gridFSDBFiles); assertNotNull(gridFSFiles);
assertThat(gridFSDBFiles.size(), is(1)); assertThat(gridFSFiles.size(), is(1));
} }
@Test @Test
@ -177,7 +182,7 @@ public class GridFSLiveTest {
String id = ""; String id = "";
try { try {
inputStream = new FileInputStream("src/main/resources/test.png"); inputStream = new FileInputStream("src/main/resources/test.png");
id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).toString();
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
logger.error("File not found", ex); logger.error("File not found", ex);
} finally { } finally {
@ -203,7 +208,7 @@ public class GridFSLiveTest {
String id = ""; String id = "";
try { try {
inputStream = new FileInputStream("src/main/resources/test.png"); inputStream = new FileInputStream("src/main/resources/test.png");
id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).toString();
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
logger.error("File not found", ex); logger.error("File not found", ex);
} finally { } finally {

View File

@ -5,8 +5,6 @@ import static org.junit.Assert.assertThat;
import java.util.List; import java.util.List;
import com.baeldung.config.MongoConfig;
import com.baeldung.model.User;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -22,6 +20,9 @@ import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.config.MongoConfig;
import com.baeldung.model.User;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class) @ContextConfiguration(classes = MongoConfig.class)
public class UserRepositoryLiveTest { public class UserRepositoryLiveTest {
@ -72,8 +73,7 @@ public class UserRepositoryLiveTest {
user.setName("Jim"); user.setName("Jim");
userRepository.save(user); userRepository.save(user);
assertThat(mongoOps.findAll(User.class).size(), is(1));
assertThat(mongoOps.findAll(User.class).size(), is(2));
} }
@Test @Test
@ -94,7 +94,7 @@ public class UserRepositoryLiveTest {
mongoOps.insert(user); mongoOps.insert(user);
user = mongoOps.findOne(Query.query(Criteria.where("name").is("Chris")), User.class); user = mongoOps.findOne(Query.query(Criteria.where("name").is("Chris")), User.class);
final User foundUser = userRepository.findOne(user.getId()); final User foundUser = userRepository.findById(user.getId()).get();
assertThat(user.getName(), is(foundUser.getName())); assertThat(user.getName(), is(foundUser.getName()));
} }
@ -106,7 +106,7 @@ public class UserRepositoryLiveTest {
mongoOps.insert(user); mongoOps.insert(user);
user = mongoOps.findOne(Query.query(Criteria.where("name").is("Harris")), User.class); user = mongoOps.findOne(Query.query(Criteria.where("name").is("Harris")), User.class);
final boolean isExists = userRepository.exists(user.getId()); final boolean isExists = userRepository.existsById(user.getId());
assertThat(isExists, is(true)); assertThat(isExists, is(true));
} }