Java Code Examples for org.springframework.data.mongodb.core.MongoTemplate

The following examples show how to use org.springframework.data.mongodb.core.MongoTemplate. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@ChangeSet(order = "01", author = "initiator", id = "01-addAuthorities")
public void addAuthorities(MongoTemplate mongoTemplate) {
    Authority adminAuthority = new Authority();
    adminAuthority.setName(AuthoritiesConstants.ADMIN);
    Authority userAuthority = new Authority();
    userAuthority.setName(AuthoritiesConstants.USER);
    mongoTemplate.save(adminAuthority);
    mongoTemplate.save(userAuthority);
}
 
Example 2
@Setup
public void setUp() throws Exception {

	client = MongoClients.create();
	template = new MongoTemplate(client, DB_NAME);

	List<RefObject> refObjects = new ArrayList<>();
	for (int i = 0; i < 1; i++) {
		RefObject o = new RefObject();
		template.save(o);
		refObjects.add(o);
	}

	ObjectWithDBRef singleDBRef = new ObjectWithDBRef();
	singleDBRef.ref = refObjects.iterator().next();
	template.save(singleDBRef);

	ObjectWithDBRef multipleDBRefs = new ObjectWithDBRef();
	multipleDBRefs.refList = refObjects;
	template.save(multipleDBRefs);

	queryObjectWithDBRef = query(where("id").is(singleDBRef.id));
	queryObjectWithDBRefList = query(where("id").is(multipleDBRefs.id));
}
 
Example 3
Source Project: secure-data-service   Source File: MongoTrackingAspect.java    License: Apache License 2.0 6 votes vote down vote up
@Around("call(* org.springframework.data.mongodb.core.MongoTemplate.*(..)) && !this(MongoTrackingAspect) && !within(org..*Test) && !within(org..*MongoPerfRepository)")
public Object track(ProceedingJoinPoint pjp) throws Throwable {

    long start = System.currentTimeMillis();
    Object result = pjp.proceed();
    long end = System.currentTimeMillis();

    if (isEnabled()) {
        MongoTemplate mt = (MongoTemplate) pjp.getTarget();
        String collection = determineCollectionName(pjp);
        proceedAndTrack(pjp, mt.getDb().getName(), pjp.getSignature().getName(), collection, start, end);
    }
    if (Boolean.valueOf(dbCallTracking)) {
        dbCallTracker.incrementHitCount();
        // dbCallTracker.addMetric("t", pjp.getSignature().toShortString(), end-start);
    }

    return result;
}
 
Example 4
@Setup
public void setUp() {

	client = MongoClients.create();
	template = new MongoTemplate(client, DB_NAME);

	source = new Person();
	source.firstname = "luke";
	source.lastname = "skywalker";

	source.address = new Address();
	source.address.street = "melenium falcon 1";
	source.address.city = "deathstar";

	template.save(source, COLLECTION_NAME);

	asPerson = template.query(Person.class).inCollection(COLLECTION_NAME);
	asDtoProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(DtoProjection.class);
	asClosedProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(ClosedProjection.class);
	asOpenProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(OpenProjection.class);

	asPersonWithFieldsRestriction = template.query(Person.class).inCollection(COLLECTION_NAME)
			.matching(new BasicQuery(new Document(), fields));

	mongoCollection = client.getDatabase(DB_NAME).getCollection(COLLECTION_NAME);
}
 
Example 5
Source Project: service-block-samples   Source File: MetricsFunction.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    };
}
 
Example 6
Source Project: microservice-recruit   Source File: IdUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取下一个id
 * @param collName
 * @param mongo
 * @return
 */
public static Long getNextId(String collName, MongoTemplate mongo) {
    Query query = new Query(Criteria.where("collName").is(collName));
    SeqInfo seq = mongo.findOne(query, SeqInfo.class);
    // 当无数据时返回0
    return (seq == null ? 0 : seq.getSeqId()) + 1;
}
 
Example 7
Source Project: maven-framework-project   Source File: UserServiceTest.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
	// test 시작전 collection 제거
	Mongo mongo = new Mongo("localhost");
	MongoTemplate mongoTemplate = new MongoTemplate(mongo, "testdb");
	mongoTemplate.dropCollection("testcollect");
}
 
Example 8
public ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
                                 final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo) {
    this.generatorStrategy = strategy;
    this.naturalKeyExtractor = extractor;
    this.mongoTemplate = mongoTemplate;
    //TODO: Fix (springify)
    this.containerDocumentHolder = new ContainerDocumentHolder();
    this.subDocAccessor = new SubDocAccessor(mongoTemplate, strategy, extractor);
    this.schemaRepo = schemaRepo;
}
 
Example 9
Source Project: chronus   Source File: AbstractMongoBaseDao.java    License: Apache License 2.0 5 votes vote down vote up
protected AbstractMongoBaseDao(MongoTemplate mongotemplate, String collectionName) {
    Type genType = getClass().getGenericSuperclass();
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    this.entityClass = (Class) params[0];
    this.collectionName = collectionName;
    this.mongotemplate = mongotemplate;
}
 
Example 10
Source Project: biliob_backend   Source File: AuthorGroupServiceImpl.java    License: MIT License 5 votes vote down vote up
@Autowired
public AuthorGroupServiceImpl(MongoTemplate mongoTemplate, CreditOperateHandle creditOperateHandle, AuthorService authorService, AuthorUtil authorUtil) {
    this.mongoTemplate = mongoTemplate;
    this.creditOperateHandle = creditOperateHandle;
    this.authorService = authorService;
    this.authorUtil = authorUtil;
}
 
Example 11
Source Project: bearchoke   Source File: UserDBInit.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public UserDBInit(CommandBus commandBus,
                  UserRepository userRepository,
                  MongoTemplate mongoTemplate) {
    this.commandBus = commandBus;
    this.userRepository = userRepository;
    this.mongoTemplate = mongoTemplate;
}
 
Example 12
Source Project: ExecDashboard   Source File: HygieiaInstanceServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param instanceRepository
 * @param hygieiaArtifactDetailsRepository
 * @param dashboardRepository
 * @param mongoTemplate
 */
@Autowired
public HygieiaInstanceServiceImpl(InstanceRepository instanceRepository,
		HygieiaArtifactDetailsRepository hygieiaArtifactDetailsRepository, DashboardRepository dashboardRepository,
		MongoTemplate mongoTemplate) {
	this.instanceRepository = instanceRepository;
	this.hygieiaArtifactDetailsRepository = hygieiaArtifactDetailsRepository;
	this.dashboardRepository = dashboardRepository;
	this.mongoTemplate = mongoTemplate;
}
 
Example 13
Source Project: sagacity-sqltoy   Source File: Mongo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @todo 取top记录
 * @param mongoTemplate
 * @param sqlToyConfig
 * @param topSize
 * @param mql
 * @param resultClass
 * @return
 */
private List<?> findTop(MongoTemplate mongoTemplate, SqlToyConfig sqlToyConfig, Float topSize, String mql,
		Class resultClass) throws Exception {
	BasicQuery query = new BasicQuery(mql);
	if (topSize != null) {
		if (topSize > 1) {
			query.limit(topSize.intValue());
		} else {
			// 按比例提取
			long count = mongoTemplate.count(query, sqlToyConfig.getNoSqlConfigModel().getCollection());
			query.limit(Double.valueOf(count * topSize.floatValue()).intValue());
		}
	}
	if (sqlToyContext.isDebug()) {
		if (logger.isDebugEnabled()) {
			logger.debug("findTopByMongo script=" + query.getQueryObject());
		} else {
			System.out.println("findTopByMongo script=" + query.getQueryObject());
		}
	}
	List<Document> rs = mongoTemplate.find(query, Document.class,
			sqlToyConfig.getNoSqlConfigModel().getCollection());
	if (rs == null || rs.isEmpty()) {
		return null;
	}
	return extractFieldValues(sqlToyConfig, rs.iterator(), resultClass);
}
 
Example 14
Source Project: sagacity-sqltoy   Source File: Mongo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param mongoFactory
 * @return
 */
private MongoTemplate getMongoTemplate() {
	if (this.mongoTemplate != null) {
		return mongoTemplate;
	}
	return (MongoTemplate) sqlToyContext.getBean(MongoTemplate.class);
}
 
Example 15
Source Project: canal-mongo   Source File: MultipleMongoConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Qualifier("completeMongoTemplate")
public MongoTemplate completeMongoTemplate() throws Exception {
    MappingMongoConverter converter =
            new MappingMongoConverter(new DefaultDbRefResolver(completeFactory()), new MongoMappingContext());
    converter.setTypeMapper(new DefaultMongoTypeMapper(null));
    return new MongoTemplate(completeFactory(), converter);
}
 
Example 16
Source Project: bearchoke   Source File: RoleDBInit.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public RoleDBInit(CommandBus commandBus,
                  MongoTemplate mongoTemplate,
                  RoleRepository roleRepository) {

    this.commandBus = commandBus;
    this.mongoTemplate = mongoTemplate;
    this.roleRepository = roleRepository;
}
 
Example 17
Source Project: Lottor   Source File: MongoTransactionOperateRepository.java    License: MIT License 5 votes vote down vote up
/**
 * 初始化操作
 *
 * @param modelName 模块名称
 * @param txConfig  配置信息
 */
@Override
public void init(String modelName, TxConfig txConfig) {
    collectionName = RepositoryPathUtils.buildMongoTableName(modelName);
    final TxMongoConfig txMongoConfig = txConfig.getTxMongoConfig();
    MongoClientFactoryBean clientFactoryBean = buildMongoClientFactoryBean(txMongoConfig);
    try {
        clientFactoryBean.afterPropertiesSet();
        template = new MongoTemplate(clientFactoryBean.getObject(), txMongoConfig.getMongoDbName());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Source Project: tutorials   Source File: ErrorLogsCounterManualTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    MongoTemplate mongoTemplate = initMongoTemplate();

    MongoCollection<Document> collection = createCappedCollection();

    persistDocument(collection, -1, LogLevel.ERROR, "my-service", "Initial log");

    errorLogsCounter = new ErrorLogsCounter(mongoTemplate, COLLECTION_NAME);
    Thread.sleep(1000L); // wait for initialization
}
 
Example 19
Source Project: Lottor   Source File: TxManagerInfoServiceImpl.java    License: MIT License 5 votes vote down vote up
public TxManagerInfoServiceImpl(DiscoveryService discoveryService, NettyConfig nettyConfig, MongoTemplate mongoTemplate,
                                RestTemplate restTemplate) {
    this.discoveryService = discoveryService;
    this.nettyConfig = nettyConfig;
    this.mongoTemplate = mongoTemplate;
    this.restTemplate = restTemplate;
}
 
Example 20
Source Project: service-block-samples   Source File: MetricsFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional
private void upsertViewList(List<View> viewList, MongoTemplate template, Map<String, Object> result) {
    viewList.forEach(view -> {
        // Find the document if it exists, if not, insert a new one
        Query updateQuery = new Query(Criteria.where("_id").is(view.getId()));

        // Increment the match count for the coupled files
        Update update = new Update().inc("matches", 1).set("lastModified", view.getLastModified());

        // Apply the increment or insert a new document
        View viewResult = template.findAndModify(updateQuery, update,
                new FindAndModifyOptions().returnNew(true).upsert(true), View.class);

        // Apply properties of a new view if the document was just inserted
        if (viewResult.getMatches() <= 1) {
            template.save(view);
            // Keep track of inserts and updates
            ((List<String>) result.get("inserted")).add(view.getId());
        } else {
            ((List<String>) result.get("updated")).add(view.getId());
            if(viewResult.getMatches() >= 2) {
                ((List<TightCouplingEvent>) result.get("events"))
                        .add(new TightCouplingEvent(view.getProjectId(), viewResult));
            }
        }
    });
}
 
Example 21
public static void ensureCaseInsensitivity(MongoTemplate mongoTemplate, String collectionName) {
    MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
    List<Document> indexes = StreamSupport.stream(collection.listIndexes().spliterator(), false).collect(Collectors.toList());
    Map<String, Document> indexPerName = indexes.stream().collect(Collectors.toMap(i -> (String) i.get("name"), Function.identity()));
    if (2 != getCollationStrength(indexPerName, "_id_", collectionName)) {
        throw new RuntimeException("Index \"_id\" in collection " + collectionName + " is not case-insensitive");
    }
    if (2 != getCollationStrength(indexPerName, "key_1", collectionName)) {
        throw new RuntimeException("Index \"key\" in collection " + collectionName + " is not case-insensitive");
    }
}
 
Example 22
@BeforeClass
public static void startMongo() throws IOException {
    factory = new MongodForTestsFactory(Version.Main.V3_5);
    MongoClient mongo = factory.newMongo();
    MongoTemplate template = new MongoTemplate(mongo, "test");
    accessor = new MongoAccessor(Arrays.asList(MongoTransactionDefinition.class), template);
}
 
Example 23
Source Project: iot-dc3   Source File: MongoConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public MongoTemplate mongoTemplate(
        MongoClientOptionProperties properties,
        MongoDbFactory factory,
        MongoMappingContext context,
        MongoCustomConversions conversions
) {
    return new MongoTemplate(mongoDbFactory(properties), mappingMongoConverter(factory, context, conversions));
}
 
Example 24
@Bean(name = "mongoTemplate")
public MongoTemplate createMongoTemplate() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(host, port);
    //TODO Configure additional MongoDB mongoClient settings if needed
    MongoDbFactory factory = new SimpleMongoDbFactory(mongoClient, database, new UserCredentials(username, password));
    MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), new MongoMappingContext());
    converter.setTypeMapper(new DefaultMongoTypeMapper(null));

    return new MongoTemplate(factory, converter);
}
 
Example 25
Source Project: biliob_backend   Source File: UserServiceImpl.java    License: MIT License 5 votes vote down vote up
@Autowired
public UserServiceImpl(
        CreditUtil creditUtil,
        UserRepository userRepository,
        VideoRepository videoRepository,
        AuthorRepository authorRepository,
        QuestionRepository questionRepository,
        UserRecordRepository userRecordRepository,
        MongoTemplate mongoTemplate,
        RefreshAuthorCreditCalculator refreshAuthorCreditCalculator,
        RefreshVideoCreditCalculator refreshVideoCreditCalculator,
        ForceFocusCreditCalculator forceFocusCreditCalculator,
        DanmakuAggregateCreditCalculator danmakuAggregateCreditCalculator,
        CheckInCreditCalculator checkInCreditCalculator,
        ModifyNickNameCreditCalculator modifyNickNameCreditCalculator,
        AuthorService authorService, CreditHandle creditHandle,
        MailUtil mailUtil,
        RecommendVideo recommendVideo, AuthorUtil authorUtil, CreditOperateHandle creditOperateHandle) {
    this.creditUtil = creditUtil;
    this.userRepository = userRepository;
    this.videoRepository = videoRepository;
    this.authorRepository = authorRepository;
    this.questionRepository = questionRepository;
    this.userRecordRepository = userRecordRepository;
    this.mongoTemplate = mongoTemplate;
    this.authorService = authorService;
    this.creditHandle = creditHandle;
    this.refreshAuthorCreditCalculator = refreshAuthorCreditCalculator;
    this.forceFocusCreditCalculator = forceFocusCreditCalculator;
    this.refreshVideoCreditCalculator = refreshVideoCreditCalculator;
    this.danmakuAggregateCreditCalculator = danmakuAggregateCreditCalculator;
    this.checkInCreditCalculator = checkInCreditCalculator;
    this.mailUtil = mailUtil;
    this.recommendVideo = recommendVideo;
    this.authorUtil = authorUtil;
    this.creditOperateHandle = creditOperateHandle;
}
 
Example 26
@Autowired
public MongoPlatformProjectionRepository(MongoPlatformRepository platformRepository,
                                         MongoModuleRepository moduleRepository,
                                         EventStorageEngine eventStorageEngine,
                                         MongoTemplate mongoTemplate,
                                         SpringProfiles springProfiles) {
    this.minimalPlatformRepository = platformRepository;
    this.platformRepository = platformRepository;
    this.moduleRepository = moduleRepository;
    this.eventStorageEngine = eventStorageEngine;
    this.mongoTemplate = mongoTemplate;
    this.springProfiles = springProfiles;
}
 
Example 27
public MongoAuthorizationProjectionRepository(MongoApplicationDirectoryGroupsRepository applicationDirectoryGroupsRepository,
                                              MongoTemplate mongoTemplate,
                                              SpringProfiles springProfiles) {
    this.applicationDirectoryGroupsRepository = applicationDirectoryGroupsRepository;
    this.mongoTemplate = mongoTemplate;
    this.springProfiles = springProfiles;
}
 
Example 28
Source Project: gaia   Source File: SettingsRepository.java    License: Mozilla Public License 2.0 4 votes vote down vote up
@Autowired
public SettingsRepository(MongoTemplate mongoTemplate, Settings settings) {
    this.mongoTemplate = mongoTemplate;
    this.settings = settings;
}
 
Example 29
Source Project: konker-platform   Source File: MongoBillingConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Override
@Bean(name = "mongoBillingTemplate")
public MongoTemplate mongoTemplate() throws Exception {
	return new MongoTemplate(this.mongo(), this.getDatabaseName());
}
 
Example 30
Source Project: spring-security-mongo   Source File: UserRepositoryImpl.java    License: MIT License 4 votes vote down vote up
public UserRepositoryImpl(final MongoTemplate mongoTemplate) {
    this.mongoTemplate = mongoTemplate;
}