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

The following examples show how to use org.springframework.data.mongodb.core.MongoTemplate. 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
Source File: InitialSetupMigration.java    From java-microservices-examples with Apache License 2.0 7 votes vote down vote up
@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
Source File: MetricsFunction.java    From service-block-samples with 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 #3
Source File: DbRefMappingBenchmark.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: ProjectionsBenchmark.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
@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 File: MongoTrackingAspect.java    From secure-data-service with 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 #6
Source File: ErrorLogsCounterManualTest.java    From tutorials with 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 #7
Source File: MongoAuthorizationProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public MongoAuthorizationProjectionRepository(MongoApplicationDirectoryGroupsRepository applicationDirectoryGroupsRepository,
                                              MongoTemplate mongoTemplate,
                                              SpringProfiles springProfiles) {
    this.applicationDirectoryGroupsRepository = applicationDirectoryGroupsRepository;
    this.mongoTemplate = mongoTemplate;
    this.springProfiles = springProfiles;
}
 
Example #8
Source File: UserServiceTest.java    From maven-framework-project with 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 #9
Source File: ContainerDocumentAccessor.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: AbstractMongoBaseDao.java    From chronus with 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 #11
Source File: IdUtil.java    From microservice-recruit with 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 #12
Source File: AuthorGroupServiceImpl.java    From biliob_backend with 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 #13
Source File: UserDBInit.java    From bearchoke with 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 #14
Source File: HygieiaInstanceServiceImpl.java    From ExecDashboard with 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 #15
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@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 #16
Source File: UserServiceImpl.java    From biliob_backend with 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 #17
Source File: Mongo.java    From sagacity-sqltoy with 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 #18
Source File: Mongo.java    From sagacity-sqltoy with 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 #19
Source File: $ Spring Data MongoDB Setup.java    From allegro-intellij-templates with Apache License 2.0 5 votes vote down vote up
@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 #20
Source File: MultipleMongoConfig.java    From canal-mongo with 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 #21
Source File: MongoConfig.java    From iot-dc3 with 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 #22
Source File: RoleDBInit.java    From bearchoke with 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 #23
Source File: MongoTransactionManagerTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: MongoConfiguration.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
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 #25
Source File: MetricsFunction.java    From service-block-samples with 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 #26
Source File: MongoTransactionOperateRepository.java    From Lottor with 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 #27
Source File: TxManagerInfoServiceImpl.java    From Lottor with 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 #28
Source File: TxManagerConfiguration.java    From Lottor with MIT License 4 votes vote down vote up
@Bean
public BaseItemService baseItemService(MongoTemplate mongoTemplate) {
    return new BaseItemServiceImpl(mongoTemplate);
}
 
Example #29
Source File: UserCommentServiceImpl.java    From biliob_backend with MIT License 4 votes vote down vote up
@Autowired
public UserCommentServiceImpl(MongoTemplate mongoTemplate, CreditHandle creditHandle, CreditOperateHandle creditOperateHandle) {
    UserCommentServiceImpl.mongoTemplate = mongoTemplate;
    this.creditHandle = creditHandle;
    this.creditOperateHandle = creditOperateHandle;
}
 
Example #30
Source File: LoginChecker.java    From biliob_backend with MIT License 4 votes vote down vote up
@Autowired
public LoginChecker(UserRepository userRepository, MongoTemplate mongoTemplate) {
    LoginChecker.userRepository = userRepository;
    LoginChecker.mongoTemplate = mongoTemplate;
}