當前位置: 首頁>>代碼示例>>Java>>正文


Java MongoTemplate類代碼示例

本文整理匯總了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);

}
 
開發者ID:nkolytschew,項目名稱:mongobee_migration_example,代碼行數:24,代碼來源:DatabaseChangeLog.java

示例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);
  }
}
 
開發者ID:nkolytschew,項目名稱:mongobee_migration_example,代碼行數:29,代碼來源:DatabaseChangeLog.java

示例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);
}
 
開發者ID:benoyprakash,項目名稱:java-hostel,代碼行數:24,代碼來源:InitialSetupMigration.java

示例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);
}
 
開發者ID:hsj-xiaokang,項目名稱:springboot-shiro-cas-mybatis,代碼行數:23,代碼來源:MongoServiceRegistryDaoTests.java

示例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);
}
 
開發者ID:nkolytschew,項目名稱:mongobee_migration_example,代碼行數:21,代碼來源:DatabaseChangeLog.java

示例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;
    };
}
 
開發者ID:kbastani,項目名稱:service-block-samples,代碼行數:27,代碼來源:MetricsFunction.java

示例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;
	}
 
開發者ID:BotMill,項目名稱:botmill-core,代碼行數:21,代碼來源:MongoDBAdapter.java

示例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");

}
 
開發者ID:KonkerLabs,項目名稱:konker-platform,代碼行數:20,代碼來源:TenantLogRepositoryTest.java

示例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
            )
    );
}
 
開發者ID:LyashenkoGS,項目名稱:analytics4github,代碼行數:22,代碼來源:MondoDbOpenshiftConfig.java

示例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));
}
 
開發者ID:Nephilim84,項目名稱:contestparser,代碼行數:19,代碼來源:EmbeddedMongoAutoConfigurationTests.java

示例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);
}
 
開發者ID:Comcast,項目名稱:dawg,代碼行數:17,代碼來源:DawgPoundMongoServiceTest.java


注:本文中的org.springframework.data.mongodb.core.MongoTemplate類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。