本文整理汇总了Java中org.springframework.data.mongodb.core.MongoTemplate类的典型用法代码示例。如果您正苦于以下问题:Java MongoTemplate类的具体用法?Java MongoTemplate怎么用?Java MongoTemplate使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
MongoTemplate类属于org.springframework.data.mongodb.core包,在下文中一共展示了MongoTemplate类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: updateUserChangeEmailField
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
/**
* update v5: {@link UserDocument} has changed; String-Field 'email' was replaced with custom Type 'Email'.
* find all user with an email String-value, replace String-Type with Custom-Type and update all UserDocuments.
* if email-Field is Empty or null, you don't have to update user.
*
* @since V6
*/
@ChangeSet(order = "006", id = "updateUserChangeEmailFromStringToCustomClass", author = "admin")
public void updateUserChangeEmailField(final MongoTemplate template) {
final Criteria isEmptyCriteria = new Criteria().orOperator(Criteria.where("email").is(""), Criteria.where("email").is(null));
while (true) {
final UserDocument result = template.findAndModify(new Query(isEmptyCriteria), Update.update("email", new Email()), UserDocument.class);
if (result == null)
break;
}
/**
* if email not null -> Field will be cast to specific class and updates will create correct entries
*/
// final Criteria isNotEmptyCriteria = new Criteria().orOperator(Criteria.where("email").ne(""), Criteria.where("email").ne(null));
// final List<UserDocument> userDocumentList = template.find(new Query(isNotEmptyCriteria), UserDocument.class);
}
示例2: updateUserChangeNameAndSurnametoName
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
/**
* update 6: {@link UserDocument} has changed; 'name' and 'surname' will be concat to 'name'.
* for each every user document get 'name' and 'surname', concat them, update 'name', remove field surname and update document.
*
* @since V7
*/
@ChangeSet(order = "008", id = "updateUserChangeNameAndSurnameToName", author = "admin")
public void updateUserChangeNameAndSurnametoName(final MongoTemplate template) {
final DBCollection userCollection = template.getCollection("user");
final Iterator<DBObject> cursor = userCollection.find();
while (cursor.hasNext()) {
final DBObject current = cursor.next();
final Object nameObj = current.get("name");
final Object surnameObj = current.get("surname");
final String updateName = (nameObj != null ? nameObj.toString() : "") + " " + (surnameObj != null ? surnameObj.toString() : "");
final BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject("name", updateName));
updateQuery.append("$unset", new BasicDBObject("surname", ""));
final BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", current.get("_id"));
userCollection.update(searchQuery, updateQuery);
}
}
示例3: addUsers
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@ChangeSet(order = "02", author = "initiator", id = "02-addUsers")
public void addUsers(MongoTemplate mongoTemplate) {
Authority adminAuthority = new Authority();
adminAuthority.setName(AuthoritiesConstants.ADMIN);
Authority userAuthority = new Authority();
userAuthority.setName(AuthoritiesConstants.USER);
User adminUser = new User();
adminUser.setId("user-0");
adminUser.setLogin("admin");
adminUser.setPassword("$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC");
adminUser.setFirstName("admin");
adminUser.setLastName("Administrator");
adminUser.setEmail("[email protected]");
adminUser.setActivated(true);
adminUser.setLangKey("en");
adminUser.getAuthorities().add(userAuthority);
adminUser.setCreatedBy(adminUser.getLogin());
adminUser.setCreatedDate(ZonedDateTime.now());
adminUser.setLastModifiedBy(adminUser.getLogin());
adminUser.setLastModifiedDate(ZonedDateTime.now());
mongoTemplate.save(adminUser);
}
示例4: verifyEmbeddedConfigurationContext
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@Test
public void verifyEmbeddedConfigurationContext() {
final PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
final Properties properties = new Properties();
properties.setProperty("mongodb.host", "ds061954.mongolab.com");
properties.setProperty("mongodb.port", "61954");
properties.setProperty("mongodb.userId", "casuser");
properties.setProperty("mongodb.userPassword", "Mellon");
properties.setProperty("cas.service.registry.mongo.db", "jasigcas");
configurer.setProperties(properties);
final FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
new String[]{"src/main/resources/META-INF/spring/mongo-services-context.xml"}, false);
ctx.getBeanFactoryPostProcessors().add(configurer);
ctx.refresh();
final MongoServiceRegistryDao dao = new MongoServiceRegistryDao();
dao.setMongoTemplate(ctx.getBean("mongoTemplate", MongoTemplate.class));
cleanAll(dao);
assertTrue(dao.load().isEmpty());
saveAndLoad(dao);
}
示例5: updateUserAddAddress
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
/**
* update v3: {@link UserDocument} has changed; an embedded Document 'address' was added.
*
* @since V4
*/
@ChangeSet(order = "004", id = "addAddressToUser", author = "admin")
public void updateUserAddAddress(final MongoTemplate template) {
final List<UserDocument> userList = template.find(Query.query(Criteria.where("email").is("[email protected]")), UserDocument.class);
userList.stream()
.map(userDocument -> {
userDocument.getUserAddress()
.addAll(
Stream.iterate(0, n -> n + 1)
.limit(new Random().nextInt(5))
.map(it -> new Address("Hamburger City", "Random Muster Straße " + it, it + "5678"))
.collect(Collectors.toList()));
return userDocument;
})
.forEach(template::save);
}
示例6: function
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@Bean
public Function<ProjectEventParam, Map<String, Object>> function(MongoTemplate template) {
return projectEventParam -> {
// Extract parameters from the event before processing
Map<String, Object> result = new HashMap<>();
result.put("updated", new ArrayList<String>());
result.put("inserted", new ArrayList<String>());
result.put("events", new ArrayList<TightCouplingEvent>());
Project project = projectEventParam.getProject();
ProjectEvent event = projectEventParam.getProjectEvent();
Commit commit = event.getPayload().getOrDefault("commit", null);
// If a commit exists and has files, create a view processor to generate query model updates
if (commit != null) {
TightCouplingProcessor tightCouplingProcessor = new TightCouplingProcessor(event, project, commit);
List<View> viewList = tightCouplingProcessor.generateView();
// Insert or update query models produced from the event
upsertViewList(viewList, template, result);
}
// Returns back a list of inserted and updated keys
return result;
};
}
示例7: setup
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
/** The mongodb ops. */
/* (non-Javadoc)
* @see co.aurasphere.botmill.core.datastore.adapter.DataAdapter#setup()
*/
public void setup() {
MongoCredential credential = MongoCredential.createCredential(
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.username"),
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"),
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.password").toCharArray());
ServerAddress serverAddress = new ServerAddress(
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.server"),
Integer.valueOf(ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.port")));
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongoClient, ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"));
MongoTemplate mongoTemplate = new MongoTemplate(simpleMongoDbFactory);
this.source = (MongoOperations) mongoTemplate;
}
示例8: defaultRepo
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@Test
public void defaultRepo() {
// Prepare context
Map<String, Object> props = new HashMap<>();
props.put("spring.data.mongodb.database", "testdb");
context = new SpringApplicationBuilder(TestConfiguration.class).web(false).properties(props).run();
// Prepare test
MongoTemplate mongoTemplate = this.context.getBean(MongoTemplate.class);
mongoTemplate.dropCollection("testapp");
MongoPropertySource ps = new MongoPropertySource();
ps.getSource().put("testkey", "testval");
mongoTemplate.save(ps, "testapp");
// Test
EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class);
Environment environment = repository.findOne("testapp", "default", null);
assertEquals("testapp-default", environment.getPropertySources().get(0).getName());
assertEquals(1, environment.getPropertySources().size());
assertEquals(true, environment.getPropertySources().get(0).getSource().containsKey("testkey"));
assertEquals("testval", environment.getPropertySources().get(0).getSource().get("testkey"));
}
开发者ID:spring-cloud-incubator,项目名称:spring-cloud-config-server-mongodb,代码行数:21,代码来源:MongoEnvironmentRepositoryTests.java
示例9: nestedPropertySource
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@Test
public void nestedPropertySource() {
// Prepare context
Map<String, Object> props = new HashMap<>();
props.put("spring.data.mongodb.database", "testdb");
context = new SpringApplicationBuilder(TestConfiguration.class).web(false).properties(props).run();
// Prepare test
MongoTemplate mongoTemplate = this.context.getBean(MongoTemplate.class);
mongoTemplate.dropCollection("testapp");
MongoPropertySource ps = new MongoPropertySource();
Map<String, String> inner = new HashMap<String, String>();
inner.put("inner", "value");
ps.getSource().put("outer", inner);
mongoTemplate.save(ps, "testapp");
// Test
EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class);
Environment environment = repository.findOne("testapp", "default", null);
assertEquals("testapp-default", environment.getPropertySources().get(0).getName());
assertEquals(1, environment.getPropertySources().size());
assertEquals(true, environment.getPropertySources().get(0).getSource().containsKey("outer.inner"));
assertEquals("value", environment.getPropertySources().get(0).getSource().get("outer.inner"));
}
开发者ID:spring-cloud-incubator,项目名称:spring-cloud-config-server-mongodb,代码行数:23,代码来源:MongoEnvironmentRepositoryTests.java
示例10: repoWithProfileAndLabelInSource
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@Test
public void repoWithProfileAndLabelInSource() {
// Prepare context
Map<String, Object> props = new HashMap<>();
props.put("spring.data.mongodb.database", "testdb");
context = new SpringApplicationBuilder(TestConfiguration.class).web(false).properties(props).run();
// Prepare test
MongoTemplate mongoTemplate = this.context.getBean(MongoTemplate.class);
mongoTemplate.dropCollection("testapp");
MongoPropertySource ps = new MongoPropertySource();
ps.setProfile("confprofile");
ps.setLabel("conflabel");
ps.getSource().put("profile", "sourceprofile");
ps.getSource().put("label", "sourcelabel");
mongoTemplate.save(ps, "testapp");
// Test
EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class);
Environment environment = repository.findOne("testapp", "confprofile", "conflabel");
assertEquals(1, environment.getPropertySources().size());
assertEquals("testapp-confprofile-conflabel", environment.getPropertySources().get(0).getName());
assertEquals(true, environment.getPropertySources().get(0).getSource().containsKey("profile"));
assertEquals("sourceprofile", environment.getPropertySources().get(0).getSource().get("profile"));
assertEquals(true, environment.getPropertySources().get(0).getSource().containsKey("label"));
assertEquals("sourcelabel", environment.getPropertySources().get(0).getSource().get("label"));
}
开发者ID:spring-cloud-incubator,项目名称:spring-cloud-config-server-mongodb,代码行数:26,代码来源:MongoEnvironmentRepositoryTests.java
示例11: shouldGetInstanceRepositoryWork
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@Test
public void shouldGetInstanceRepositoryWork()
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// workaround to get valid impl template
Field f = tenantLogRepository.getClass().getDeclaredField("mongoAuditTemplate");
f.setAccessible(true);
MongoTemplate mongoTemplate = (MongoTemplate) f.get(tenantLogRepository);
TenantLogRepository repository = TenantLogRepository.getInstance();
// workaround to set impl template
Field fSet = repository.getClass().getDeclaredField("mongoAuditTemplate");
fSet.setAccessible(true);
fSet.set(repository, mongoTemplate);
repository.insert("YJgQ8Zj2j0", new Date().getTime(), "WARN", "H5ITwKKqrm");
}
示例12: getMongoTemplate
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
private MongoTemplate getMongoTemplate(String host, int port,
String authenticationDB,//TODO: is it redundant ?
String database,
String user, char[] password)
throws UnknownHostException {
return new MongoTemplate(
new SimpleMongoDbFactory(
new MongoClient(
new ServerAddress(host, port),
Collections.singletonList(
MongoCredential.createCredential(
user,
authenticationDB,
password
)
)
),
database
)
);
}
示例13: assertVersionConfiguration
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
private void assertVersionConfiguration(String configuredVersion,
String expectedVersion) {
this.context = new AnnotationConfigApplicationContext();
int mongoPort = SocketUtils.findAvailableTcpPort();
EnvironmentTestUtils.addEnvironment(this.context,
"spring.data.mongodb.port=" + mongoPort);
if (configuredVersion != null) {
EnvironmentTestUtils.addEnvironment(this.context,
"spring.mongodb.embedded.version=" + configuredVersion);
}
this.context.register(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class);
this.context.refresh();
MongoTemplate mongo = this.context.getBean(MongoTemplate.class);
CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }");
assertThat(buildInfo.getString("version")).isEqualTo(expectedVersion);
}
开发者ID:vikrammane23,项目名称:https-github.com-g0t4-jenkins2-course-spring-boot,代码行数:19,代码来源:EmbeddedMongoAutoConfigurationTests.java
示例14: assertVersionConfiguration
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
private void assertVersionConfiguration(String configuredVersion,
String expectedVersion) {
this.context = new AnnotationConfigApplicationContext();
int mongoPort = SocketUtils.findAvailableTcpPort();
EnvironmentTestUtils.addEnvironment(this.context,
"spring.data.mongodb.port=" + mongoPort);
if (configuredVersion != null) {
EnvironmentTestUtils.addEnvironment(this.context,
"spring.mongodb.embedded.version=" + configuredVersion);
}
this.context.register(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class);
this.context.refresh();
MongoTemplate mongo = this.context.getBean(MongoTemplate.class);
CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }");
assertThat(buildInfo.getString("version"), equalTo(expectedVersion));
}
示例15: testUnReserveWithValidDevice
import org.springframework.data.mongodb.core.MongoTemplate; //导入依赖的package包/类
@Test
public void testUnReserveWithValidDevice() {
MongoTemplate mockMongoTemplate = EasyMock.createMock(MongoTemplate.class);
PersistableDevice persistableDev = EasyMock.createMock(PersistableDevice.class);
DawgPoundMongoService dawgPoundService = new DawgPoundMongoService();
ReflectionTestUtils.setField(dawgPoundService, "mongoTemplate", mockMongoTemplate);
EasyMock.expect(mockMongoTemplate.findById(TestConstants.DEVICE_ID, PersistableDevice.class, TestConstants.COLLECTION_NAME )).andReturn(persistableDev);
EasyMock.expect(persistableDev.unreserve()).andReturn(TestConstants.TOKEN);
mockMongoTemplate.save(persistableDev, TestConstants.COLLECTION_NAME);
EasyMock.replay(mockMongoTemplate, persistableDev);
Assert.assertEquals(dawgPoundService.unreserve(TestConstants.DEVICE_ID), TestConstants.TOKEN);
EasyMock.verify(mockMongoTemplate, persistableDev);
}