Java教程

MongoDB在SpringBoot中使用

本文主要是介绍MongoDB在SpringBoot中使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.引用

        <!-- mongo -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2.配置

####################mongodb##########################
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/earth

earth是db名,在创建db时还需要创建至少一个collection(类似table)

3.方法调用

@Component
public class MongoComponent {

    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    
    /**
     * 
     * @param brand
     */
    public void save(BrandEntity brand) {
        
        
        mongoTemplate.save(brand);        
    }
    
    
    /**
     * 
     * @param registerNum
     * @return
     */
    public BrandEntity findByRegisterNum(String registerNum) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
    
        return mongoTemplate.findOne(q, BrandEntity.class);
    }
    
    
    /**
     * 
     * @param registerNum
     */
    public void deleteByRegisterNum(String registerNum) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
                
        mongoTemplate.remove(q, BrandEntity.class);
    }
    
    
    /**************************Collection************************/
    
    
    /**
     * 
     * @param brand
     * @param collectionName
     */
    public void saveInCollection(BrandEntity brand, String collectionName) {
        
        
        mongoTemplate.save(brand, collectionName);
    }
        
    
    /**
     * 
     * @param registerNum
     */
    public void deleteByRegisterNumInCollection(String registerNum, String collectionName) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
                
        mongoTemplate.remove(q, BrandEntity.class, collectionName);
    }
    
    /**
     * 
     * @param registerNum
     * @param collectionName
     * @return
     */
    public BrandEntity findOneByRegisterNumInCollection(String registerNum, String collectionName) {
        
        Query q = new Query(Criteria.where("registerNum").is(registerNum));
        
        return mongoTemplate.findOne(q, BrandEntity.class, collectionName);
    }
    
    
    /**
     * 
     * @param sTime
     * @param eTime
     * @param collectionName
     * @return
     */
    public List<BrandEntity> findByIntervalInCollection(Date sTime, Date eTime, String collectionName) {
        
        Query q = new Query(Criteria.where("updateTime").gte(sTime).lte(eTime));
        
        
        return mongoTemplate.find(q, BrandEntity.class, collectionName);
        
    }
}

 

这篇关于MongoDB在SpringBoot中使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!