安装MongoDB

安装MongoDB

MongoDB用户、数据库相关命令操作

https://www.jianshu.com/p/237a0c5ad9fa

# 创建用户以及角色
use springboot-db db.createUser({ user: 'ydd', pwd: '123456', roles:[{ role: 'root', db: 'springboot-db' }] }) # 进行用户认证 use springboot-db db.auth('ydd', '123456')
# 更新用户权限 db.updateUser("ydd",{roles:[ {role:"root",db:"springboot-db"} ]}) 注:updateuser它是完全替换之前的值,如果要新增或添加roles而不是代替它 则使用方法: db.grantRolesToUser() 和 db.revokeRolesFromUser() //删除数据库 dbTest db.dbTest.drop() show users // 查看当前库下的用户 db.dropUser('testadmin') // 删除用户 db.updateUser('admin', {pwd: '654321'}) // 修改用户密码 MongoDB 数据库默认角色 数据库用户角色:read、readWrite 数据库管理角色:dbAdmin、dbOwner、userAdmin 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager 备份恢复角色:backup、restore 所有数据库角色: readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、 dbAdminAnyDatabase 超级用户角色:root

 

依赖

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

 

接口

package com.vast.dao;

import com.vast.entity.Account;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface AccountRepository  extends MongoRepository<Account, Integer> {
    public Account findByName(String name);
}

写一个接口,继承MongoRepository,这个接口有了几本的CURD的功能。如果你想自定义一些查询,比如根据firstName来查询,获取根据lastName来查询,只需要定义一个方法即可。注意firstName严格按照存入的mongodb的字段对应。在典型的java的应用程序,写这样一个接口的方法,需要自己实现,但是在springboot中,你只需要按照格式写一个接口名和对应的参数就可以了,因为springboot已经帮你实现了。

 

测试

package com.vast;

import com.vast.dao.AccountRepository;
import com.vast.dao.IAccountMybatisDao;
import com.vast.entity.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationVastStart.class)
public class TestAccountService {

    @Autowired
    private IAccountMybatisDao accountMybatisDao;
    @Autowired
    private AccountRepository accountRepository;

    @Test
    public void TestSaveAccount(){
        Account account = new Account();
        account.setName("222");
        account.setMoney(23.9);
////        accountMybatisDao.saveAccount(account);
//        accountRepository.findByName("");
        System.out.println(accountRepository.findAll());
//        System.out.println(accountRepository.insert(account));
    }
}

 

posted on 2019-12-09 16:02  风又奈何  阅读(596)  评论(0编辑  收藏  举报